+ 7

How macros work in C works ?

I have tried to make a macro for simple square calculations but it won't work when i pass an expression to it... Any idea why it is happening? And output? https://code.sololearn.com/cRZOeBTWA09N/?ref=app

6th Jul 2019, 12:15 PM
Aaditya Deshpande
Aaditya Deshpande - avatar
3 ответов
+ 10
#define square(x) x*x Macro arguments are evaluated after macro expansion. macro definition replaces corresponding values before compilation . if you write say #define square(n) n*n it'll replace all square(n) with n*n .. remember before compilation. printf("\nsquare(4-2)) = %d",square(4-2)); this is on of the statements where you are getting wrong output logically. let's elaborate. square(4-2) will be replaced with 4-2*4-2 not 2*2. this is because replacement happenes before compilation without caring 4-2 will be 2. due to operator precedence 4-2*4-2 will be 4-(2*4)-2=4-8-2=-6. same logic for others 😊 it's recommended to avoid using macros with parameters but here is a quick fix for your program. just replace your macro definition with this: #define square(x) (x)*(x) hope you understand. *refer also : https://www.geeksforgeeks.org/interesting-facts-preprocessors-c/
6th Jul 2019, 12:32 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 6
Cool Thanks dude 👍
6th Jul 2019, 12:44 PM
Aaditya Deshpande
Aaditya Deshpande - avatar
+ 6
6th Jul 2019, 12:45 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar