Home > Mobile >  Hidden rocks of func3(func1(), func2())?
Hidden rocks of func3(func1(), func2())?

Time:09-28

Is there any problem of using another function call as a function parameter in C?

int foo1(int a){return a  ;}
int foo2(int b){return b  ;}
int foo3(int a, int b){return a b;} 

int result = foo3(foo1(1),foo2(2)); /*result is 5 */

CodePudding user response:

To expand on tstanisl's comment

int foo1(int a) { puts("ONE"); return a  ; }
int foo2(int b) { puts("TWO"); return b  ; }
int foo3(int a, int b) { return a b; } 

int result = foo3(foo1(1),foo2(2));

There is no specific order for the prints. Any of

ONE                                     TWO
TWO                                     ONE

is possible. Can even change next time you recompile (or run) your executable!

CodePudding user response:

There's no problem with the code in your question.

That code looks very much like it's intended to demonstrate a potential problem with calls like foo3(foo1(1),foo2(2)), but it fails to do so.

For example:

int foo1(int a){return a  ;}

The expression a has a side effect, but one that's irrelevant. The parameter a is a local variable, and it ceases to exist when the function returns. It might as well be just return a; (except for possible undefined behavior if the increment overflows).

This:

int n = 42;
int func(int param) { return param  ; }

returns the value 42 and does not affect the value of n. The applies to a copy of n, not to n itself. Function arguments in C are passed by value.

The potential problem with that kind of call is that the order of the evaluation of the arguments is unspecified. The calls foo1(1) and foo2(2) have no side effects that are visible to the caller, but a call like foo3(a , a ) would, and could yield different results depending on the unspecified order in which the arguments are evaluated. (I'm not 100% certain whether that case has undefined behavior; it depends on whether there's a sequence point between the evaluations of the arguments. But that uncertainty alone is more than enough reason to avoid writing code like that.)

  •  Tags:  
  • c
  • Related