4

Possible Duplicate:
C Macros and use of arguments in parentheses

I found this macro question to be very interesting.

If this following code is defined as a Macro

#define MULT(x, y) x * y

And the function call is made as int z = MULT(3 + 2, 4 + 2);. The Desired output is 3+2=5 and 4+2=6 And 5*6 to be 30.

But the returned output was 13. It takes it as 3+2*4+2. Hence according to the precedence of operators it evaluates 2*4 first.

What is the fix here? In case of smaller functions like these which one is efficient? Defining the function or using the macros?

Community
  • 1
  • 1
Katti
  • 2,013
  • 1
  • 17
  • 31

2 Answers2

12

Try something like:

#define MULT(x, y) ((x)*(y))
aztaroth
  • 979
  • 7
  • 13
0

Try this:

#define MULT(x, y) ((x) * (y))

Personally, I think it's more readable (and fewer keystrokes) to not use the macro. This is the kind of thing that someone will start adding to their code in the rush of learning new things and regret later on.

duffymo
  • 305,152
  • 44
  • 369
  • 561