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 */ }
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).
An example would be ADD : ADD(1,2) and ADD(2,1) can be used interchangeably, the order of parameters does not matter.
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?.
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
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