Alex Rivera | Logout

C programming ++ operator

Asked 2010-01-14T19:42:34.253
12

Why does this code always produce x=2?

unsigned int x = 0;
x++ || x++ || x++ || x++ || ........;
printf("%d\n",x);
Edit
Report

3 Answers

5

|| short-circuits. Evaluated from left, when a true value is found (non-zero) it stops evaluating, since the expression now is true and never can be false again.

First x++ evaluates to 0 (since it's post-increment), second to 1 which is true, and presto, you're done!

answered 2010-01-14T19:45:31.970
1

Because logical OR short-circuits when a true is found.

So the first x++ returns 0 (false) because it is post-increment. (x = 1) The second x++ returns 1 (true) - short-circuits. (x = 2)

Prints x = 2;

answered 2010-01-14T19:46:47.643
1

Because of early out evaluation of comparisons.

This is the equivalent of

 0++ | 1++

The compiler quits comparing as soon as x==1, then it post increments, making x==2

answered 2010-01-14T19:46:50.547

Your Answer