# Thread: x *= x++ + ++x;

1. ## x *= x++ + ++x;

I want to understand clearly how pre and post increment ops work.

Code:
int main()
{
x = 1;
x *= x ++ + ++ x;
printf("\n %d \n ",x);
}
The highlighted expression above can be seen as follows:

x op1 x op2 op3 op4 x

The C Operator Precedence Chart gives the following order of precedence:

op4 followed by op2 followed by op3 followed op1 (?)
... which means the following happens:

1. 2 is returned to the expression after op4 happens. Now, the value of x in memory becomes 2 (?)

2. 2 is returned to the expression after op2 happens. Now the value of x in memory becomes 3 (?)

3. 4 is returned to the expression after op3 happens. No change to x.

4. op1 evaluates to 3 * 4 which means x becomes 12.

But the output of the program is 8. Which means that in step 4, op1 still reads the value of x as 2 not 3 ? why?

2. Anything could happen, the expression is undefined because you modify x more than once between sequence points.

3. when i run the code with tc3,the result is 9,why?

5. the pre/post in/de-crement operators are just a matter of when the increment occurs. if it's pre, then then increment is performed before evaluation. if it's post, the increment is peformed after evaluation. run the following:

Code:
#include <iostream>
using std::cout;
using std::endl;
int main()
{
char hello[] = "Hello World";
char *p;

//POST
p = hello;
cout << *p++ << endl;
cout << *p << endl << endl;

//PRE
p = hello;
cout << *++p << endl;
cout << *p << endl;
return 0;
}

6. Originally Posted by misplaced
the pre/post in/de-crement operators are just a matter of when the increment occurs. if it's pre, then then increment is performed before evaluation. if it's post, the increment is peformed after evaluation.

Quzah.

7. We get this question often enough that you would think everyone with more than 20 posts would know the answer by now.

8. Even worse than that, however, is the fact that some teachers quiz students on innane stuff like this -- and they're wrong!

9. http://www.eskimo.com/~scs/C-faq/q3.2.html
Yeah I know Dave said it, and everyone else said it as well, so I just thought I'd say it again just incase some noobs simply don't get it.

The last noob who tried to argue their way out of the pits of hell.
http://cboard.cprogramming.com/showt...ight=undefined