> Help with increment operators in C?

Help with increment operators in C?

Posted at: 2014-12-18 
You cannot predict the output of that code. Different compilers may produce different results.

In fact, I tried your code with Microsoft C. If I compile in debug mode, I get exactly the same results you do. If I switch to Release mode (which enables optimizations), I get:

5 5

7 7

6 6

6 5

Same code, same compiler, different results.

C does not define what the output of your program will be. The spec says this:

"If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined."

i is your scalar object. Pre and Post increment have side effects. Parameters to a function (printf in your case) are unsequenced. See link.

Do not write code that relies on undefined behavior.

I would say that you should NOT expect to be able to predict the output.

Obviously, the compiler has to evaluate one of the expressions before the other, but you should never count on the order when the same variable is incremented in the same statement. You should NEVER write code like these examples.

Hello everyone,

For this script

int x = 5;

printf("%d %d\n", x++, x++);

x = 5;

printf("%d %d\n", ++x, ++x);

x = 5;

printf("%d %d\n", x++, ++x);

x = 5;

printf("%d %d\n", ++x, x++);

the output is

6 5

7 7

6 7

7 5

please explain how did the post and pre increment operators worked... or in other words, how can I predict the output by looking at the script.

Thanks