0

I was given a variation of this C code in an interview recently, and asked what would be returned by the function.

#define fun(a) a*a

int main() {    
  return(fun(4+5));   
}

I've run it with a printf("%d"...) in place of the return and it prints 29. No other types than "%d" showed a result. Can someone explain what is going on here?

DYZ
  • 55,249
  • 10
  • 64
  • 93

1 Answers1

11

a is expanded, not evaluated as a. So you get:

4+5*4+5 

and with operator priorities; you get 4 + 20 + 5 => 29

better way (with extra outside parenthesis for protecting against outside operators too thanks to Thomas comment):

#define fun(a) ((a)*(a))

but all parenthesis of the world still don't protect against i++, function calls (with side effects, preferably)... so argument reusing in macros is always a problem (there's no syntax to declare & assign a temp variable either). Prefer inlined functions in that case.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219