问题
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:
- submit argument
a
- submit argument
a++
- submit argument
++a
- increment
a
for++a
- increment
a
fora++
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:
The function arguments order of evaluation is unspecified. Therefore, either
++a
ora++
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.
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