#include<stdio.h>
#define mul(p,q) p*q
int main(){
int a=5;
printf("%d",mul(a+3,a-2));
return 0;
}
I expected this to print 24, but I got 18. Why is that happening?
#include<stdio.h>
#define mul(p,q) p*q
int main(){
int a=5;
printf("%d",mul(a+3,a-2));
return 0;
}
I expected this to print 24, but I got 18. Why is that happening?
It's basically, find and replace before compiling. Your code becomes
int main(){
int a=5;
printf("%d",a+3*a-2);
return 0;
}
instead of #define mul(p,q) p*q
you should do #define mul(p,q) ((p)*(q))
. Then your code would become as below and you would get the expected answer.
int main(){
int a=5;
printf("%d",((a+3)*(a-2)));
return 0;
}
Whenever the preprocessor does something surprising to your code, you can find out what it was by inspecting the preprocessed output. With a Unixy compiler, use the -E
command-line option:
$ gcc -E test.c | sed -ne '/main/,$p'
int main(){
int a=5;
printf("%d",a+3*a-2);
return 0;
}
(The sed bit is to eliminate thousands of lines of irrelevant material produced by the inclusion of stdio.h
.)
Macro expansion has produced
printf("%d",a+3*a-2);
Do you understand why you get a surprising answer now?
This is a very common problem people have with the C preprocessor. The GNU CPP manual has an entire section entitled "Operator Precedence Problems" discussing it. The short version is that your macro definition should have been
#define mul(p,q) ((p)*(q))