C中函数调用中后缀或前缀递增的未定义行为 [英] Undefined Behavior of Postfix or Prefix Increment in Function Calls in C

查看:117
本文介绍了C中函数调用中后缀或前缀递增的未定义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在本网站看到,函数调用中的前缀增量或后缀增量可能导致未定义的行为。我最近经历了其中一次。源代码如下所示:

I have seen in this site that prefix increment or postfix increment in a function call may cause undefined behavior. I have gone through one of those recently. The source code is something like this :

#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?另外,为什么++从12减少到11?有人可以请解释一下吗?谢谢。

The output comes out as 12 11 12****14 13 14***_. But, when a is printed first in the function, shouldn't it be 10? Why does it become 12? Also, why does a++ decrease from 12 to 11? Can someone please kindly explain? Thank you.

推荐答案

这是未定义的行为,因此完全取决于编译器的执行顺序操作完成:

That is undefined behaviour and as such it is entirely up to the implementation of the compiler in which order the following operations are done:


  1. 提交参数 a

  2. 提交参数 a ++

  3. 提交参数 ++ a li>
  4. 增量 a ++ a

  5. a ++
  6. 增加 a
  1. submit argument a
  2. submit argument a++
  3. submit argument ++a
  4. increment a for ++a
  5. increment a for a++

编译器知道的唯一事情是:2.必须在5和4之前发生。

The only thing that the compiler knows is: 2. has to happen before 5. and 4. has to happen before 3.

您正在观察:

You are observing:

++a;
submit argument 2
a++;
submit the other arguments

这篇关于C中函数调用中后缀或前缀递增的未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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