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.
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.
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.
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.
If the counter is a complex type and the result of the increment is used, then pre increment is typically faster than post increment.
Well, there are two things to consider with your example code:
++a
or a++
is evaluated first is implementation-dependent.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With