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/23368530/

相关文章:

c - 如何使用 C 预处理器重载函数返回类型(仅限 C)

c - C 编译器的行为差异示例

c - 静态缓冲区和非初始化静态缓冲区

r - 如何将具有相同协变量的个体的二项式响应数据分解为伯努利,反之亦然?

c - 输出返回错误结果

java - x = x++ 不会递增,因为++ 是在赋值后应用的?

c++ - 目标文件中 undefined reference - 如何找到哪个库包含它?

python - 如何在python中停止这个while循环

c - 在 printf 中发布增量和指针

java - i++ 和 i+1 在数组计数上的区别