Can any one explain how macros in C works....? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can any one explain how macros in C works....?

I have questions regarding this way of using MACRO, #define sqr(x) x*x printf ("%d", sqr(3-5)); It print (-17)..... I concluded that it works in this way 3(-5)+3-5 = -17 But i can't understand why it's work this way, If i pass a single integer, like sqr(2) it return square of it, i.e. 4... Can any one explain first case....

29th Apr 2020, 2:57 AM
DeWill
DeWill - avatar
2 Answers
+ 2
Macros are simple text substitutions. When the preprocessor processes a macro it just does the equivalence of a copy-paste operation. So the argument you pass in ( 3 - 5 ) is copied for each occurrence of 'x' in the macro. x * x translates to 3 - 5 * 3 - 5 and because of precedence rules is interpreted as 3 - (5 * 3) - 5. This is one of the common pitfalls of macros. Another similar one is sqr(n++) where it's translated n++ * n++ and you get a sequence point error but it isn't very obvious because you only incremented the value once. So it can be helpful if you think of macros as copy/paste operations, use them with care, and also capitalize them so you don't mistake them for functions. It's a good idea to parenthesize the entire macro expression (it may not matter much here, but it's a good rule to follow to prevent weird parsing mistakes): #define SQR(x) ((x) * (x)) The parenthesized arguments would've evaluated your expression as intended.
29th Apr 2020, 3:16 AM
Damyian G
Damyian G - avatar
0
Gotcha.... Thanks a lot.... 👍🏻👍🏻
30th Apr 2020, 12:35 PM
DeWill
DeWill - avatar