How are arguments evaluated in a function call?

Consider this code:

void res(int a,int n)
{
    printf("%d %d, ",a,n); 
}

void main(void) 
{
    int i; 
    for(i=0;i<5;i++)
        res(i++,i);
    //prints 0 1, 2 3, 4 5

    for(i=0;i<5;i++)
        res(i,i++);
    //prints 1 0, 3 2, 5 4
}

Looking at the conclusion, it seems that the arguments are not evaluated right to left every time. What exactly is going on here?

+3
source share
2 answers

The evaluation order of the arguments in the function call is not specified. The compiler can evaluate them depending on what order it can decide.

From the standard C99 6.5.2.2/10 "Functional Calls / Semantics":

The order of evaluation of the function pointer, the actual arguments and the subexpressions in the actual arguments are not defined, but there is a sequence point before the actual call.

If you need to provide a specific order, using time series is the usual workaround:

int i; 
for(i=0;i<5;i++) {
    int tmp = i;
    int tmp2 = i++;

    res(tmp2,tmp);
}

( undefined, ), , increment/decment . , :

. , , . (6.5/2 "" )

+7

: . , , ( ). , undefined. FAQ 3.2. , , , .

, : , . (. , Q2 GOTW # 56.)

. , , .

: main int.

+3

Source: https://habr.com/ru/post/1736390/


All Articles