+ 6

#define , why in this example the answer is 10, but not 15?

#include <stdio.h> # define prod(i,j) i*j int main() { int x=3, y=4; printf("%d", prod(x+2,y-1)); return 0; }

20th Jan 2019, 2:47 PM
Zhenis Otarbay
Zhenis Otarbay - avatar
2 Answers
+ 5
Because macro function behave weirdly, what actually happens is the preprocessor replaces prod(x+2,y-1) with x+2*y-1 so the equation becomes 3+2*4-1 which is equal to 10 and not 15 if you want it to work just add parentheses prod((x+2),(y-1)) this should fix it
20th Jan 2019, 3:10 PM
Mohamed Ali ZORGATI
Mohamed Ali ZORGATI - avatar
+ 3
3+2*4-1=10 write: # define prod(i,j) (i)*(j) or printf("%d", prod((x+2),(y-1))); then you get (3+2)*(4-1)=15
20th Jan 2019, 3:25 PM
Игорь Яковенко
Игорь Яковенко - avatar