+ 1

How while() work without condition instead with increment?

how this code work and what is output? int a=2; int b=3; while(b--) ++a; cout<<a;

24th Nov 2016, 7:34 AM
MerzaT
MerzaT - avatar
7 odpowiedzi
+ 5
while() works with a boolean conditionals in this case, 'b' variable is the conditional, as 0 is considered false, and all other values are considered true so 'b' is decremented each iteration until reaching 0, and then the conditional does not return true anymore, causing the loop to break
24th Nov 2016, 7:43 AM
Burey
Burey - avatar
+ 3
without while? and without cout?
24th Nov 2016, 7:51 AM
Burey
Burey - avatar
+ 3
i just ran it as well in the c++ compiler in the code playground got 5 as expected... mind posting the full code including main and include?
24th Nov 2016, 7:55 AM
Burey
Burey - avatar
+ 3
tnx now it works correctly...
24th Nov 2016, 8:12 AM
MerzaT
MerzaT - avatar
+ 2
Burey covered the "how" pretty well, so I'll stick with the output: int a=2; no output, a=2 int b=3; no output, b=3 while(b--) ++a; no output, b=3[-1 after], a=3 No output again, b=2[-1 after], a=4 No output again, b=1[-1 after], a=5 No output again, b=0 -- 0 == false, loop broken. cout<<a; outputs: 5
24th Nov 2016, 8:03 AM
Matthew Shephard
Matthew Shephard - avatar
0
so if i change a and b value like this a=3 b=2 it return no output!!! what is problem?
24th Nov 2016, 7:48 AM
MerzaT
MerzaT - avatar
0
no int a=3; int b=2; while(b--) ++a; cout<<a; i mean this code just change value
24th Nov 2016, 7:53 AM
MerzaT
MerzaT - avatar