Possible Duplicate:
Undefined Behavior and Sequence Points
I am using microsoft visual c++. Look at the following example:
int n = 5;
char *str = new char[32];
strcpy(str, "hello world");
memcpy(&str[n], &str[n+1], 6+n--);
printf(str);
// output is "hell world"
So unexpectadly my compiler produces code that first decrements n and then executes memcpy. The following source will do what i expected to happen:
int n = 5;
char *str = new char[32];
strcpy(str, "hello world");
memcpy(&str[n], &str[n+1], 6+n);
n--;
printf(str);
// output is "helloworld"
First I tried to explain it to myself. The last parameter gets pushed on the stack first, so it may be evaluated first. But I really believe that post increment/decrement guarantee to be evaluated after the next semicolon.
So I ran the following test:
void foo(int first, int second) {
printf("first: %i / second: %i", first, second);
}
int n = 10;
foo(n, n--);
This will output "first: 10 / second: 10".
So my question is: Is there any defined behaviour to this situation? Can somebody point me to a document where this is described? Have I found a compiler bug ~~O.O~~?
The example is simplyfied to not make sence anymore, it just demonstrates my problem and works by itself.