我在这个网站上看到函数调用中的前缀增量或后缀增量可能会导致未定义的行为。我最近经历了其中一个。源代码是这样的:
#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?有人可以解释一下吗?谢谢。
您的示例代码需要我们考虑两件事:
The function arguments order of evaluation is unspecified. Therefore, either ++a
or a++
is evaluated first but it is implementation-dependent.
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 */