+ 1
[SOLVED] I didn't understand how this code works. Maybe someone can help!
int a = 0, b = 0; while (a < 7, b < 17) { a++; b++; } printf("%d, %d\n", a, b);
6 ответов
+ 4
while( a < 17, b < 17 )
Here we have 2 expressions to evaluate, as loop condition. The 2 expressions are chained by comma operator, which evaluates its operands from left to right. Comma operator evaluates both operands, but only the rightmost operand ( b < 17 ) will be counted for as the final evaluation result.
That is why <a> and <b> are both incremented until <b> value equals to 17.
http://www.c4learn.com/c-programming/c-comma-operator/
+ 2
I found this Stackoverflow question and answer interesting
https://stackoverflow.com/questions/4072578/inside-a-while-loop-is-the-last-comma-separated-statement-guaranteed-to-run-las
+ 1
The expression a<7 is having no effect, because 17 is greater than 7 so when the variables 'a' and 'b' inside while become 16 then 16<17 so a and b gets incremented to 17(both). Then they get printed.
if you will use while(a<7 || b<17)
output will be 17,17
and for while(a<7 && b<17)
output will be 7,7 because of &&
in your case complier will also give warning.
+ 1
Thanks! Ipang
0
Thanks! HK Lite
0
What an interesting explanation! Thanks! Paul K Sadler