Wednesday, February 13, 2008

C function calls order of computation

Demo of order of computation in the C program.

It shows case, where functions called for calculation of arguments called in order, different to left-to-right in which expression is writen.

gcc (GCC) 4.1.3 20070929 (prerelease)
used.


------------%<-----------------------
#include

int my_func(int arg1, char *arg2){
printf ("d=%d, s=%s\n", arg1, arg2);
return 0;
}

int main()
{
int i;
char *my;
my = "ad";
i = 5;
my_func(i,(my_func(1,"da"),my));
return my_func(1,"da");
}
------------>%-----------------------


gcc tst.c
./a.out

d=1, s=da
d=5, s=ad
d=1, s=da



modify my_fun:
-return 0;
+return arg1;


and main:
-my_func(i,(my_func(1,"da"),my));
+my_func((my_func(2,"two"),
+ my_func(3,"three"),
+ (my_func(4,"four"))), (my_func(5,"five"),
+ "six", "seven"));


recompile;
output will be:
d=5, s=five
d=2, s=two
d=3, s=three
d=4, s=four
d=4, s=seven
d=1, s=da


Second argument of outer call to my_func calculated first in the second example.

<---------->
This order is not specified in standard, and can be different for different compilers, and different for the same compiler.

Thats why functional style of programming in C and C++ is not acceptable option for me.

No comments: