cout << (--i)-- << " "; and the answer is?

Thread Starter

summeranson

Joined Feb 12, 2009
28
If i = 5, what will be the result of:

do
{
cout << (--i)-- << " ";
} while(i>=2 && i < 5);


A. It won't enter the loop


B. It will loop forever

C. I don't know


D. Compiler error


E. 4 3 2 1


F. 4 3 2


G. 4 2 1


H. 4 2
 

mik3

Joined Feb 4, 2008
4,843
I think the answer is A because i=5 and it will never enter the loop.

Another possible answer is D because of (--i)-- but I think it is possible to use both --i and i-- in C but with a slightly different functionality.
 

odinhg

Joined Jul 22, 2009
65
The answer is H.

i = 5;
do{
cout << (--i)-- << " ";
} while(i>=2 && i < 5);


First it will enter the loop before checking that i>=2 and i<5 because it's a do-while loop.

Then it will decrease i by 1 and print it (i-1 = 4), then decrease it by 1 another time.

Now i is 3 and i>=2&&i<5 is true, so it will run the loop again.

Decrease i with 1, which gives us 2 and print it, then decrease it with 1 another time.

Now i is 1, so i>=2&&i<5 is false and the loop stops.
 
Top