Search code examples
cwhile-loopinfinite-looplogical-operatorsassignment-operator

Combined assignment operator in a while loop condition in C


I really have a hard time understanding how the following piece of code works:

int x = -2;

while ( --x > -10 && (x -= 2)) {
    printf ( " %d," , x ) ;
}
printf ( " %d" , x ) ;

output:   -5, -8, -11, -12

I mean I get what

while ( --x > -10)

output:  -3, -4, -5, -6, -7, -8, -9, -10

and

while (x -= 2)

output: -> infinte loop

alone would do, but how do they work with the and operator? I mean for "while (x -= 2)" the condition is only met when x = 2, so how can the while loop even end and not go infinite like it does when only "while (x -= 2)" is used?


Solution

  • The code is unnecessarily obfuscated...

    You are right that while ( x -= 2 ) would result in an infinite loop.

    However, C has (what are known as) short circuit operators.

    Thus in the expression while ( --x > -10 && (x -= 2) ) the second term is only evaluated when the first term is true.

    Therefore, while the first term --x > -10 holds true, the second term (x -= 2) is also evaluated... once the first term becomes false, the second term is not evaluated, and the loop exits with just the single pre-decrement... resulting in the output you observe.