Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top