C/C++ post-increment/-decrement and function call [duplicate]

雨燕双飞 提交于 2019-12-06 09:32:20

问题


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.



来源:https://stackoverflow.com/questions/14695681/c-c-post-increment-decrement-and-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!