Please explain this answer 😓 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
30th Mar 2021, 4:02 PM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
5 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 ).
30th Mar 2021, 4:07 PM
Shadow
Shadow - avatar
+ 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))
30th Mar 2021, 4:10 PM
Slick
Slick - avatar
+ 1
Hey Martin Taylor , But your explanation also too good 😊
30th Mar 2021, 4:13 PM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
+ 1
Thanks Slick 😊
30th Mar 2021, 4:14 PM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
0
Thanks Shadow 😊
30th Mar 2021, 4:09 PM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar