How does the decrement operator work in a while statement?

I have the following source code in C:

#include<stdio.h> void main() { int i=0, x=3; while((x---1)) { i++; } printf("%d", i); } 

How does this while statement work and why does it print 2 instead of 1?

+6
source share
4 answers

Because x---1 really just x-- - 1 , which gives the value x - 1 until x decreases.

Given that x has an initial value of 3, the cycle runs 2 times (once with x = 3, once with x = 2, then next time x is 1, so x - 1 is 0, and the cycle no longer works).

So, i starts at 0, and it doubles, so it ends at 2.

+10
source

(x---1) == (x-- -1)

, because the compiler first tries to select a larger token, so --- interpreted as -- and -

The expression x-- - 1 means the first 1 subtracted from the current x value due to - minus the operation. Then, the x value decreased by 1 due to the postfix decrement operator -- .

For example, before the first iteration x = 3 , therefore, under condition 2 (i.e. 3 - 1 ) after that x decreases and before the next iteration x = 2 .

x = 3 , i =0 ;

  • 1 iteration: while(2) , and in loop i becomes 1

x = 2 , i = 1;

  • 2 iteration: while(1) , and in loop i becomes 2

x = 1 , i = 2;

  • Now x - 1 = 0 , which gives while(0) , and the loop breaks and i do not increase.

So, after the exit of the cycle i : 2

pay attention to one more point: i does not increase as a loop break, because i++ in while-block {} , but x reduced to 0 . After the loop, if you type f x , then the output will be 0 .

+5
source

So it probably makes sense if you look at it with a few more spaces:

 while( ( x-- - 1) ) 

A post-decrement is used, so x changes after returning its current value, so it is really equivalent to this:

 while( ( x - 1) ) 

and the loop will run until the expression is false or in this case 0 , which is equivalent to false . Thus, the launch is performed as follows:

 xx - 1 i ============= 3 2 1 x - 1 not 0 so increment i 2 1 2 x - 1 not 0 so increment i 1 0 2 Loop exits here and does not increment i again 

At this point, the loop ends and you press printf .

+3
source

while((x---1)) equivalent to while((x-- -1 != 0)) , which in turn is the same as while(x-- != 1) . Since the value of x-- is the value of x before decrement, this is the same as

 while(x != 1) { x--; ... } 

which runs twice if x starts at 3.

+2
source

Source: https://habr.com/ru/post/950627/


All Articles