Ad

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?

Ad

Answer

The test is purposely obfuscated. Here are the steps:

  • --x > -10 always decrements x and compares the resulting value to -10, breaking from the loop if x reaches -10 or below.
  • if x >= -10 from the previous test, (x -= 2) further decreases the value of x by 2 and tests whether the resulting value is non zero. The only value of x for which (x -= 2) is zero is x = 2. In the present case, x is always negative so this test is always true.

starting from x = -2, the iterations are:

  • --x -> x = -3, the comparison is true
    (x -= 2) -> x = -5, printf outputs -5

  • --x -> x = -6, the comparison is true
    (x -= 2) -> x = -8, printf outputs -8

  • --x -> x = -9, the comparison is true
    (x -= 2) -> x = -11, printf outputs -11

  • --x -> x = -12, the comparison is false, the loop is exited

  • the final printf outputs -12

Ad
source: stackoverflow.com
Ad