c - C 函数调用中后缀或前缀递增的未定义行为

标签 c function post-increment pre-increment

<分区>

我在这个网站上看到函数调用中的前缀增量或后缀增量可能会导致未定义的行为。我最近经历了其中一个。源代码是这样的:

#include <stdio.h>

void call(int,int,int);
int main()
{
    int a=10;
    call(a,a++,++a);
    printf("****%d %d %d***_\n",a,a++,++a);
    return 0;
}

void call(int x,int y,int z)
{
    printf("%d %d %d",x,y,z);
}

输出结果为 12 11 12****14 13 14***_。但是,当函数中首先打印 a 时,它不应该是 10 吗?为什么会变成12?另外,为什么 a++ 从 12 减少到 11?有人可以解释一下吗?谢谢。

最佳答案

您的示例代码需要我们考虑两件事:

  1. The function arguments order of evaluation is unspecified. Therefore, either ++a or a++ is evaluated first but it is implementation-dependent.

  2. Modifying the value of a more than once without a sequence point in between the modifications is also undefined behavior.

因为第 2 点,你在这里有双重未定义的行为(你做了两次)。注意未定义的行为并不意味着什么都没有发生;这意味着任何都可能发生。

call(a,a++,++a); /* UB 1 */
printf("****%d %d %d***_\n",a,a++,++a); /* UB 2 */

关于c - C 函数调用中后缀或前缀递增的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42301291/

相关文章:

C 标准库的综合开源测试套件

c - 我正在尝试使用 C 编码从 linux 制作 uniq 命令

c++ - 引用类型返回函数和后缀增量

c - 如何有选择地将二维数组的列或行传递给函数?

c - inode的设备是什么?

javascript - 单击链接时如何设置 Javascript "name"?

javascript - javascript中的 "return+"是什么意思

swift - 为什么我的一个 segues 不工作?

c++ - 知道为什么下面的代码片段打印 2 而不是 3

c -++ 与指针的 += 1 相同吗?