Undefined Behavior of Postfix or Prefix Increment in Function Calls in C [duplicate]

醉酒当歌 提交于 2019-12-17 16:53:43

问题


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);
}

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.


回答1:


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. submit argument a
  2. submit argument a++
  3. submit argument ++a
  4. increment a for ++a
  5. increment a for a++

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



回答2:


There are two things your example code requires us to consider:

  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.

Because of point 2, you have double undefined behavior here (you do it twice). Note undefined behavior doesn't mean nothing happens; it means anything can happen.

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



回答3:


The C and C++ standards do not indicate an order of evaluation for function arguments. To be blunt, it is not incorrect for a compiler to cause the parameters to be evaluated from right to left, or left to right.

The best answer is, Stay Away from this type of 'Undefined Behavior'; as it can lead to subtle portability problems.




回答4:


There's no requirement that a be equal to anything; that's what is meant by undefined behavior. It's entirely up to the compiler to evaluate the arguments to call and to printf in any order it sees fit, because the language does not specify what order they need to be evaluated.



来源:https://stackoverflow.com/questions/23368530/undefined-behavior-of-postfix-or-prefix-increment-in-function-calls-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!