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

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

问题描述

可能重复:结果
  未定义行为和顺序点

我使用微软的Visual 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"

所以我unexpectadly编译器生成code的第一递减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--);

这将输出第一:10 /秒:10。

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

所以我的问题是:有没有任何定义的行为,这种情况呢?有人能指出我到这是描述的文档?我找到一个编译器错误~~ O.O ~~?

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

这个例子是simplyfied不使SENCE了,它只是本身证明了我的问题和作品。

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

推荐答案

有在作怪两个相关的问题。首先,函数参数的执行顺序为未指定。什么是有保证的是,所有正在进入函数的主体之前执行。第二,它是的未定义的行为,因为你正在改变和阅读 N 如果没有这些前pressions之间的序列点。

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 ++后增量/ -decrement和函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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