I have a question regarding Increment Operators | SoloLearn: Learn to code for FREE!

0

I have a question regarding Increment Operators

PROGRAM 1: int main() { int x,y; x=10; x=x++; x=x++; x=x++; x=x++; cout<<"Value of x= " <<x<<endl; return 0; } //output: Value of x =10 PROGRAM 2: int main() { int x,y; x=10; y=x++; y=x++; y=x++; y=x++; cout<<"Value of Y= " <<y<<endl; return 0; } //output: Value of x =13 Why the Output of Program 1 is "10" not "13"?? Why the value of x is not increasing as in program 2?

12/27/2019 5:19:34 PM

Aryan Gupta

3 Answers

New Answer

+2

Because first of all you are doing post increment so it first assigns the value and then it is incremented. int x = 10; x = x++; // RHS x is still 10 and it is again assigned to x which means the value never increments. But in program 2 you are not assigning x to x again so it is incremented and value is updated to give you a new result.

+3

Aryan Gupta In first program the result is undefined by Standard. This is C++ x = x++; has a sequence point issue. The result you are getting is compiler dependent. In second program x is assigned to different variable hence things are fine, value is incrementing according to posincrement rules.

0

Thank You Avinesh. I didn't see that way at all.