Is the increment in case of an expression involving x++ always made after the variable to be copy to a function ?
The call :
foo(x++, y);
The function :
int foo(int x, int y)
{
return x*y;
}
Is that a undefined behavior for all compilers?
Is the increment in case of an expression involving x++ always made after the variable to be copy to a function ?
The call :
foo(x++, y);
The function :
int foo(int x, int y)
{
return x*y;
}
Is that a undefined behavior for all compilers?
Let's see the official descriptions here to get a deeper understanding.
For the postfix operator, quoting C11, chapter §6.5.2.3
The result of the postfix
++operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). [...] The value computation of the result is sequenced before the side effect of updating the stored value of the operand.
and, regarding the function call, chapter §6.5.2.3
There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call. Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.
So, as per above description, there's nothing problematic in your code as shown above.
The old value of x is passed and then, the value is increased.
However, please note the last part of the second quote, you need to maintain the sanity of the code. For example, you need to make sure, there's no change in value without having a sequence point in between. Something like
foo(x++, x++, y);
will be a problem as, you're trying to changing the same variable (x) more than once.
Consider the following program
#include <stdio.h>
int x;
void foo(int x1 )
{
extern int x;
printf( "x1 = %d\n", x1 );
printf( "x = %d\n", x );
}
int main(void)
{
foo( x++ );
return 0;
}
Its output is
x1 = 0
x = 1
Thus as it is seen the value of the expression x++ is the value of the operand before incrementing
x1 = 0
However the side effect was applied before the function gets the control
x = 1
The program is well-formed and there is no undefined behavior.
Whenever post increment is used, the original value of the variable will be sent to the function. And after that, the value of x will be incremented.