Increment and Decrement Operators

2019-09-19 20:08发布

#include <stdio.h>

int main()
{
int x = 4, y, z;
y = --x;
z = x--;
printf("%d %d %d", x, y, z);
}

Output: 2 3 3

Can anyone explain this?
And what does i =+ j mean (suppose i = 1 and j = 2)?

12条回答
y = --x;

X is decremented, then Y is assigned with the value of X (3)

z = x--;

Z is assigned with the value of X (3), the X is decremented (2)

You have to understand the notions of post-decrement and pre-decrement operator.

Both will decrement your variable, but one of them will return the original value (x--) and one of them will return the decremented value (--x).

Postfix decrement (x--) is different from prefix decrement (--x). The former return the value x, then decrements it; the latter decrements and then returns the value.

And if you thing how a postfix is written at low level, you'll find that it is a liiiitle slower than the prefix... :)

simple explanation:

--x or ++x : Value will be modified after.

x-- or x++ : Value will be modified before

Detailed explanation:

--x or ++x: pre-decrement/increment: will first do the operation of decrementing or incrementing first, then it will assign x.

x-- or x++: post:decrement/increment: will first assign the value of x and then it will do the operation of decrementing or incrementing after.

lets write your code in a nicer format and go through your code step by step and annotate it to show you visually what happens:

main() {
//We declare the variables x, y and z, only x is given a value of 4.
int x=4,y,z;

//--x will decrement var x by 1 first THEN it will assign the value of x to y.
//so: x = 3, y = 3 and z = nothing yet.
y = --x;

//x-- will assign the value of x to z first, then var x will be decremented by 1 after.
//so: x = 2, y=3 and z = 3
z = x--;

printf ("\n %d %d %d", x,y,z);

}

Talking about what i=+j; means(given i=1 and j=2)

i=+j; is equivalent to i=i+j; so your expression becomes i=1+2 i.e. i=3

The postfix decrement operator (x--) returns the value of the variable before it was decremented.

• x = 2, because you've decremented it twice.
• y = 3, because you've assigned it to the value of x after it was decremented from 4
• z = 3, because you've assigned it to the value of x before it was decremented from 3.