C/C++ post-increment/-decrement and function call

2020-07-25 08:58发布

问题:

This question already has answers here:
Closed 7 years ago.

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.

回答1:

There are two related issues at play. First, the order of execution of function arguments is unspecified. What is guaranteed is that all are executed before entering the body of the function. Second, it is undefined behaviour because you are changing and reading n without any sequence points between those expressions.