Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming Macros multiplication [duplicate]

Tags:

c

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?

like image 387
Katti Avatar asked Sep 12 '25 05:09

Katti


1 Answers

Try something like:

#define MULT(x, y) ((x)*(y))
like image 126
aztaroth Avatar answered Sep 13 '25 22:09

aztaroth