C / C ++后增量/减量和函数调用 [英] C/C++ post-increment/-decrement and function call

查看:124
本文介绍了C / C ++后增量/减量和函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

未定义的行为和序列点

c ++。看下面的例子:

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"

所以我的编译器生成的代码 first 递减n,然后执行memcpy。下面的源代码会做我期望发生的事情:

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.

所以我运行以下测试:

void foo(int first, int second) {
    printf("first: %i / second: %i", first, second);
}
int n = 10;
foo(n, n--);

这将输出first:10 / second:10。

This will output "first: 10 / second: 10".

所以我的问题是:这种情况有没有明确的行为?有人可能指向我描述这个文件吗?我发现了一个编译器错误~~ OO ~~?

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~~?

这个例子是简单的不再使sence了,它只是演示了我的问题和工作本身。 >

The example is simplyfied to not make sence anymore, it just demonstrates my problem and works by itself.

推荐答案

有两个相关的问题。首先,函数参数的执行顺序为未指定。所保证的是,在进入函数体之前执行所有的函数。第二,是未定义行为,因为您正在更改并读取 n ,而且这些表达式之间没有任何序列点。

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.

这篇关于C / C ++后增量/减量和函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆