Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter evaluation order before a function calling in C [duplicate]

Can it be assumed a evaluation order of the function parameters when calling it in C ? According to the following program, it seems that there is not a particular order when I executed it.

#include <stdio.h>  int main() {    int a[] = {1, 2, 3};    int * pa;      pa = &a[0];    printf("a[0] = %d\ta[1] = %d\ta[2] = %d\n",*(pa), *(pa++),*(++pa));    /* Result: a[0] = 3  a[1] = 2    a[2] = 2 */     pa = &a[0];    printf("a[0] = %d\ta[1] = %d\ta[2] = %d\n",*(pa++),*(pa),*(++pa));    /* Result: a[0] = 2  a[1] = 2     a[2] = 2 */     pa = &a[0];    printf("a[0] = %d\ta[1] = %d\ta[2] = %d\n",*(pa++),*(++pa), *(pa));    /* a[0] = 2  a[1] = 2 a[2] = 1 */  } 
like image 690
corto Avatar asked Dec 17 '08 22:12

corto


People also ask

What is evaluation order of function parameters in C?

evaluation order and sequence pointsOrder of evaluation of the operands of any C operator, including the order of evaluation of function arguments in a function-call expression, and the order of evaluation of the subexpressions within any expression is unspecified (except where noted below).

Does order matter for parameters?

An example would be ADD : ADD(1,2) and ADD(2,1) can be used interchangeably, the order of parameters does not matter.


2 Answers

No, function parameters are not evaluated in a defined order in C.

See Martin York's answers to What are all the common undefined behaviour that c++ programmer should know about?.

like image 81
Grant Wagner Avatar answered Sep 29 '22 20:09

Grant Wagner


Order of evaluation of function arguments is unspecified, from C99 §6.5.2.2p10:

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

Similar wording exists in C89.

Additionally, you are modifying pa multiple times without intervening sequence points which invokes undefined behavior (the comma operator introduces a sequence point but the commas delimiting the function arguments do not). If you turn up the warnings on your compiler it should warn you about this:

$ gcc -Wall -W -ansi -pedantic test.c -o test test.c: In function ‘main’: test.c:9: warning: operation on ‘pa’ may be undefined test.c:9: warning: operation on ‘pa’ may be undefined test.c:13: warning: operation on ‘pa’ may be undefined test.c:13: warning: operation on ‘pa’ may be undefined test.c:17: warning: operation on ‘pa’ may be undefined test.c:17: warning: operation on ‘pa’ may be undefined test.c:20: warning: control reaches end of non-void function 
like image 40
Robert Gamble Avatar answered Sep 29 '22 20:09

Robert Gamble