Trung Đặng Trung Đặng - 1 month ago 12
C Question

Macro and similar function return different results

I'm quite confusing about this:

#define prod(x,y) x*y


The following function call prints
11
in the console:

printf("%d",prod(1+2,3+4));


But when I use
prod(x,y)
as a function returning
x*y
, it returns 21.
Why the results are different? I thought
#define
should give
prod(x,y) = x*y
.

Answer

Operator precedence is biting you.

With

#define prod(x,y) x*y

the line

printf("%d",prod(1+2,3+4));

gets expanded to

printf("%d",1+2*3+4);

Note that * has higher precedence than +, so this is evaluated as 1 + (2 * 3) + 4 or 11.

Solution:

Surrround the parameters with parenthesis in your #define:

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

The line will now be expanded to:

printf("%d",((1+2)*(3+4)));

The purpose of the extra set of parenthesis around the entire expression is to make the expression work as you want when used in conjunction with an operator where evaluation order matters.

prod(4,3)/prod(1,2)) gets expanded to ((4)*(3))/((1)*(2)) or 6. Without the outer parenthesis the expansion would be (4)*(3)/(1)*(2) or 24.