Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 804
thulasi Avatar asked Jun 07 '10 13:06

thulasi


People also ask

Which has higher precedence post increment or pre increment?

The precedence of post increment is more than precedence of pre increment, and their associativity is also different. The associativity of pre increment is right to left, of post increment is left to right.

Does i ++ or ++ i matter in a for loop?

This means that there is sequence point in for loop after every expression. So, it doesn't matter whether you do ++i or i++ or i+=1 or i=i+1 in the 3rd expression of for loop.

How does pre increment and Post increment work in for loop?

Pre increment directly returns the incremented value, but post increments need to copy the value in a temporary variable, increment the original and then returns the previous made copy.

Which is faster Preincrement and Postincrement?

If the counter is a complex type and the result of the increment is used, then pre increment is typically faster than post increment.


1 Answers

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
like image 54
James McNellis Avatar answered Sep 27 '22 17:09

James McNellis