MOHIT SINGHANIA MOHIT SINGHANIA - 1 month ago 18
C Question

How MACROS work in C?

#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?

Answer

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;
}