0
Please explain this answer đ
7 Answers
+ 6
A macro is just text replacement, so sqr( 3 + 1 ) is expanded to 3 + 1 * 3 + 1 = 7. Use parentheses if you have to worry about something like that happening, e.g. #define sqr( x ) ( x ) * ( x ).
+ 4
#include <stdio.h>
#define sqr(x) x*x
int main() {
printf("%d",sqr(3+1));
return 0;
}
when the preprocessor goes through before the program is compiled, it will replace the call to the macro sqr(x) with its definition
#include <stdio.h>
#define sqr(x) x*x
int main() {
printf("%d",3+1*3+1); // order of operations
return 0;
}
...
3+1*3+1
3+3+1
7
to fix this, you must put variables in parenthesis when defining a macro
#define sqr(x) ((x)*(x))
+ 1
Hey Martin Taylor ,
But your explanation also too good đ
+ 1
Thanks Slick đ
0
Thanks Shadow đ