# Mailinglist Archive: opensuse-programming (32 mails)

 < Previous Next >
##### Re: [suse-programming-e] post increment and self assignment problem
• From: Sedat DOÐRU <sdogru@xxxxxxxxxxxx>
• Date: Sat, 06 Jul 2002 14:53:34 +0200
• Message-id: <3D26E84E.6030508@xxxxxxxxxxxx>
Hello,
The postincrement operator does NOT have a higher priority than assignment. First, the assignment is done, then the increment is done. The preincrement operator has a higher presedence than assignment (++x). With preincrement, first the variable is incremented then the result is assigned.
And your problem is not with operator presedence. Let me explain you what happens for x step by step:
1. x is created in the memory and the value 10 is assigned
2. x is assigned to x, in other words value of x is set to value of x (so x is 10)
3. The value stored in x is incremented by 1 (so now x is 11)
4. x is printed to the stdout (the printed value is 11)
In your code it seems as if you are trying to print the old value of x (the value before the increment). For this to happen you should use

z = x++;
cout << "x = " << z << '\n';

x = x++;
cout << "x = " << x << '\n';

This way you will be able to print the old value. To make the things quite clear
1. x is created in the memory and the value 10 is assigned
2. x is assigned to z, in other words value of z is set to value of x (so z is 10)
3. The value stored in x is incremented by 1 (so now x is 11)
4. z is printed to the stdout (the printed value is 10).

Verdi March wrote:

Hi,
I'd like to ask a (basic) question about operator post inc (lvalue++).
I've this code fragment:

/**************/
int y = 10;
int z;
z = y++;
cout << "z = " << z << '\n';

int x = 10;
x = x++;
cout << "x = " << x << '\n';
/**************/

The execution results in:
z = 10
x = 11

I'm confused why x became 11, because the post inc. operator has
higher precedence than assignment, so given an expressoin x = x++, x++ is evaluated first. The signature for post inc. is T operator++(int).
So the return value of x++ is 10 (x itself will be modified to 11), but
then the expression of x = (x++) become x = ret_val_of_x_plus_plus,
which is x = 10? Am I correct?

Regards,
Verdi

--
Sedat Dogru
__________________________________________________
blue tec IT services ag

Sedat Dogru
Project Manager

80689 München
Germany

+49 - 89 - 700 76 43- 46

mail: sdogru@xxxxxxxxxxxx
internet: www.blue-tec.net

 < Previous Next >