#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
)?
#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
)?
X is decremented, then Y is assigned with the value of X (3)
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:
Talking about what
i=+j;
means(given i=1 and j=2)i=+j;
is equivalent toi=i+j;
so your expression becomesi=1+2
i.e.i=3
The postfix decrement operator (x--) returns the value of the variable before it was decremented.