C Programming - Expressions - Discussion

Discussion Forum : Expressions - Find Output of Program (Q.No. 8)
8.
What will be the output of the program?
#include<stdio.h>
int main()
{
    int x=4, y, z;
    y = --x;
    z = x--;
    printf("%d, %d, %d\n", x, y, z);
    return 0;
}
4, 3, 3
4, 3, 2
3, 3, 2
2, 3, 3
Answer: Option
Explanation:

Step 1: int x=4, y, z; here variable x, y, z are declared as an integer type and variable x is initialized to 4.
Step 2: y = --x; becomes y = 3; because (--x) is pre-decrement operator.
Step 3: z = x--; becomes z = 3;. In the next step variable x becomes 2, because (x--) is post-decrement operator.
Step 4: printf("%d, %d, %d\n", x, y, z); Hence it prints "2, 3, 3".

Discussion:
26 comments Page 2 of 3.

Kavipriya said:   7 years ago
I didn't get it. Please explain.

Abhi said:   7 years ago
Please Explain me.

Siri said:   8 years ago
y=--x means first x is decremented and then assign x value to y.

So, here x=4, x is decremented so x= 3 then assign x to y hence y=3.z=x-- means first x value is assigned to z and then x value is decremented hence z=3 and x=2.

Jeeth said:   1 decade ago
Can anyone explain this.

Ninad said:   9 years ago
Thanks @Raj.

Raj said:   9 years ago
Y =--x in this case x is decremented first and then after the value of x is assigned to y. So x becomes 3 and y is also 3.

Z =x-- here first the value of x is assigned to z first and then it is decremented so z is 3 and x becomes 3 - 1 = 2.

Gunu said:   9 years ago
I didn't get how x=2?

Bhaggu said:   9 years ago
After excution the value is done with inc/dec operation in the case of post, in that case how the value become as 2?

Vensi said:   9 years ago
How the value of x becomes?

Sayli said:   9 years ago
How x becomes 2? What is the function of post increment operator?


Post your comments here:

Your comments will be displayed after verification.