-1

What is wrong with this code? The answer should be 24 for this question right?

int t; 
vector<int>arr={24,434};

for(int i=arr.size()-1;i>=(arr.size()-2);i--)
{

        t=i;
}

cout<<arr[t];
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • ***What is wrong with this code*** Why do you feel something is wrong with this code? Do you face any issues? – kiner_shah Jan 20 '22 at 08:01
  • 1
    Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to [edit] your questions to improve them, like telling us the expected and actual behavior, and what efforts at *debugging* you have made. – Some programmer dude Jan 20 '22 at 08:02
  • 1
    Add `cout << i < – Jason Jan 20 '22 at 08:03
  • 2
    You have infinite loop, cast result of `arr.size()` to int. – rafix07 Jan 20 '22 at 08:03
  • 3
    And where did you get the shown code from? Did you write it yourself? Is it part of some assignment or exercise? An exam perhaps? Or an interview? I wonder because the loop doesn't make much sense, and might actually lead to undefined behavior if there was only a single element in the vector. – Some programmer dude Jan 20 '22 at 08:04
  • You could have seen a warning message "comparison of signed and unsigned integer values" thrown by the compiler if you enabled warnings during compilation. – kiner_shah Jan 20 '22 at 10:34

2 Answers2

1

This loop

for(int i=arr.size()-1;i>=(arr.size()-2);i--)

is an infinite loop.

When i is equal to 0 it is decremented due to the third expression of the loop and becomes equal to -1.

And then in this condition

i>=(arr.size()-2)

as the operand arr.size()-2 has unsigned integer type with the rank not less than the rank of an object of the type int then due to the usual arithmetic conversions the expression i is converted to the unsigned integer type that corresponds to the type of the expression arr.size()-2 and becomes a very big value due to promoting the bit sign.

That is in this expression

i>=(arr.size()-2)

the left operand can not be a negative value.

In fact this loop

for(int i=arr.size()-1;i>=(arr.size()-2);i--)

does not make a sense because in any case there can be no more than one iteration.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Your loop never ends. Because an unsigned integer can never be -1.

Instead, try this smart approach:

#include <iostream>
#include <vector>


int main( )
{
    std::vector<int> arr { 24, 434 };
    std::size_t t { };

    for ( std::size_t idx { arr.size( ) }; idx--; )
    {
            t = idx;
    }

    std::cout << arr[ t ];
}

Output:

24

As you can see, the loop header does not have an update section, and the condition section also performs the task of decrementing.

digito_evo
  • 3,216
  • 2
  • 14
  • 42