Why is cout within the while condition parenthesis? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is cout within the while condition parenthesis?

int x = 5; while (x && cout << x--); Why is cout within the while condition parenthesis? What is the x left of the logical AND operator comparing to? How come the output is 54321? Where would I begin to figure out this output?

28th Jul 2020, 6:19 AM
Solus
Solus - avatar
3 Answers
+ 3
If we want to print a variables when checking conditions we declare like that with in parenthesis. This loop print x - value and then decrement x. So that 5 then 4 3 2 1. When reach 0 the conditions fails loop was stop.
28th Jul 2020, 6:43 AM
Azhagesanヾ(✿)
Azhagesanヾ(✿) - avatar
+ 1
I'm guessing the value of <x> is the one considered as loop condition here. As we noticed the loop stops when <x> value reaches zero (a falsey value). The short-circuit evaluation of logical AND only evaluates the RHS (cout << x--) while <x> value not equals zero (cmiiw).
28th Jul 2020, 7:06 AM
Ipang
+ 1
Ipang Could it also be that we're evaluating it like 'while (X&&Y)' where Y is cout << x--, an action item that is always true? Of course, when either X or Y becomes zero, (X&&Y) would evaluate to false.
29th Jul 2020, 5:11 AM
Solus
Solus - avatar