x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 227

# Simple C question

hi experts,

below is a very simple C code,
int x=4,y,z;
y=--x;
z=x--
printf ("\n%d %d %d ",x,y,z);

i got the output as 2, 3, 3. I am just wondering how did i get 2 for x. If it is because of --x and x--, then how i got z=3?
Could anyone explain this please. i appreciate the help. and thanks in advance.
considor, novice in C so pls explain in a simple way.
0
deepthiji
• 3
• 3
1 Solution

Commented:
Hi

It's because x-- sets z to equal x which is three, then decreases x by 1 so x is now 2

Regards,
Zyloch
0

Commented:
To make it more clear:

y=--x;       //because you're using -- before x, it sets y to x-1, so y equals 3. x also equals 3 now.
z=x--;       //because you're using -- after x, it sets z to equal x, which is 3, then decreases x, so x=2

Regards
0

Author Commented:
so are you saying x--  = x and x-1. , what i am wondering is why the above equation did not give the value of x-- to z, it gave the value of x to z right?
thats why z=3,
So could you tell me how the compiler works? it wont check the whole equation?  little bit confused,

0

Author Commented:
if the whole value of (x--) would have gone to z, then z should be 2 right?
as you said it sets z=x first and then decrease x by one. when we write equation like this z=x--. are we supposed to get the whole value  of right had side to z? please explain, Sorry to ask this question . might be a foolish one.
thanks
0

Commented:
Don't worry.

The reason there is --x and x-- is not just for convenience. If it helps, just think of it from left to right.

z = x--;
z = --x;

The first line does does the expression on that line and THEN after that expression is complete (in this case setting z to x), it decreases x. The second one drecreases x BEFORE it assigns x to z.

This concept can get a little confusing at times. Think about it this way:

z=x --
z= --x
(don't write it this way, heh)

Even though you don't type it this way, it makes it clearer. In the first one, z=x first then does the --. The second one, z = --x

Regards,
\${Zyloch}
0

Author Commented:
i started learnning C, couple of days back, hope i will get the hang of it when i learn more.
I understood about --x and x-- now i guess>)
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.