+ 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);

18th Aug 2021, 10:55 PM
mesarthim
mesarthim - avatar
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/
18th Aug 2021, 11:29 PM
Ipang
19th Aug 2021, 3:59 AM
Paul K Sadler
Paul K Sadler - avatar
+ 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.
18th Aug 2021, 11:19 PM
HK Lite
HK Lite - avatar
+ 1
Thanks! Ipang
19th Aug 2021, 6:24 AM
mesarthim
mesarthim - avatar
0
Thanks! HK Lite
19th Aug 2021, 6:23 AM
mesarthim
mesarthim - avatar
0
What an interesting explanation! Thanks! Paul K Sadler
19th Aug 2021, 6:24 AM
mesarthim
mesarthim - avatar