Reputation: 11
do {instructions...}
while (x--)
should first do the instructions, then check if x
is not 0
and go on/or leave the loop according to result and only after all these operations decrement x
.
But my compiler decrements first.
Who is wrong? Me or my compiler ;-)? Could You please explain me why?
Upvotes: 1
Views: 152
Reputation: 108978
Many expressions in C have a value and a side-effect.
For the expression x--
the value is the value x
had before; and the side-effect is decrementing x
's value.
So, if you start with x
being 1, when the execution reaches that expression, it will yield the value 1
and set x
to 0. The next time the expression is evaluated, the value is 0
and x
is set to -1
, ...
Upvotes: 3
Reputation: 3871
What You are saying
should first do the instructions, then check if 'x' is not '0' and go on/or leave the loop according to result AND ONLY AFTER ALL THESE OPERATIONS DECREMENT 'x'
What should be
should first do the instructions, then check if 'x' is not '0', then DECREMENT 'x' and go on/or leave the loop according to result
Upvotes: 3
Reputation:
the flow is :
1) do instructions
2) check value of x
3.1) is x == 0? then do x-- (x becomes -1) and exit the loop
3.2) is x != 0? then do x-- and go to step 1)
Upvotes: 1