Reading Code (Postfix/PreFix Increment) / Precedence

The following prints 7, but I do not see how.

I read that a prefix increment (++x) increments the value of x, whereas a post fix increment (x++) increments the value of x only after other operations have been performed on it.

When I work through this it seems like it should print "4". Perhaps I am messing up the precedence. But here is my reasoning:

For "int k = n++ * -3" the n is incremented in a postfix manner. So I have to perform the operation on it first and then increment. So I take 'n', which is -1, and multiply it with -3. So I get 3. Then I increment. So I get 4. Then I assign 4 to k.

For "++n * 4 + k" the n is incremented in a prefix manner, so I increment prior to performing any operations on it. So the relevant calculation would be 0 * 4 + k, which is 0 * 4 + 4. But this is equal to 4, not 7. What am I doing wrong? I would appreciate any help.

1
2
3
4
5
6
int main()
{
int n = -1;
int k = n++ * -3;
cout << ++n * 4 + k << endl;
}
Last edited on
 
int k = n++ * -3;
is equivalent to
1
2
int k = n * -3;    
n = n + 1;


and
 
cout << ++n * 4 + k << endl;
is equivalent to
1
2
n = n + 1;  
cout << n * 4 + k << endl;



Thus the complete sequence is like this:
1
2
3
4
5
6
7
8
    int n = -1;                // n is -1

    int k = n * -3;            // n is -1.   k is +3
    n = n + 1;                 // n is 0


    n = n + 1;                 // n is +1
    cout << n * 4 + k << endl; // output 1 * 4 + 3 
Thank you!
Topic archived. No new replies allowed.