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];
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.