This question already has an answer here:
I am new to c language. I just wanted to know why is my macro not working properly. It is giving me output as 13 where as my expected output is 24.?
#include<stdio.h>
#define mult(a,b) a*b
int main()
{
int x=4,y=5;
printf("%d",mult(x+2,y-1));
return 0;
}
mult(x+2,y-1)
expands tox +2 * y -1
that is equals to4 + 2 * 5 -1
gives output:13
.You might be expecting answer
(4 + 2) * (5 -1)
=6 * 4
=24
. To make it expand like this you should write parenthesize macro as @H2Co3 also suggesting:Read aslo: So, what's wrong with using macros? by Bjarne Stroustrup.
Because it replaces the arguments literally:
Try changing the define to:
In this case the result after pre-processing is this:
This will solve the problem but it's still not the best way to do it.
This version is considered as good practice because in other types of situation the first one would fail. See the bellow example:
In this case it would give an incorrect answer because it is translated by the pre-processor to the fallowing:
printing 34 instead of 100.
For the ((a)+(b)) version it would translate to:
giving a correct answer.
Use parentheses in the macro definition
This is because different arithmetic operators have different precedence levels. Hence always use parentheses while defining the macro.
This is because C macros are simple textual substitutions, the macro writer must be sure to insert parentheses around every macro variable when it is substituted, and around the macro expansion itself, to prevent the resulting expansion from taking on new meanings.
If you observe your program:
mult(a, b)
is defined asa * b
The Correct way would be: