Order of operations for pre-increment and post-increment in a function argument?

thulasi picture thulasi · Jun 7, 2010 · Viewed 16.9k times · Source

I have some C code:

main()
{
    int a=1;
    void xyz(int,int);

    xyz(++a,a++);     //which Unary Operator is executed first, ++a or a++?

    printf("%d",a);
}
void xyz(int x,int y)
{
    printf("\n%d %d",x,y);
}

The function xyz has two parameters passed in, ++a and a++. Can someone explain the sequence of operations to explain the result?

The above code prints "3 13" or "2 23" depending on which compiler is used.

Answer

James McNellis picture James McNellis · Jun 7, 2010

Well, there are two things to consider with your example code:

  1. The order of evaluation of function arguments is unspecified, so whether ++a or a++ is evaluated first is implementation-dependent.
  2. Modifying the value of a more than once without a sequence point in between the modifications results in undefined behavior. So, the results of your code are undefined.

If we simplify your code and remove the unspecified and undefined behavior, then we can answer the question:

void xyz(int x) { }

int a = 1;
xyz(a++); // 1 is passed to xyz, then a is incremented to be 2

int a = 1;
xyz(++a); // a is incremented to be 2, then that 2 is passed to xyz