Code: #include<stdio.h> #define SQR(x) x * x int main() { printf("%d", 225/SQR(15)); } why this program outputs 225 instead of 1 (according to calculation).
The macro is substituted like the following , Code: #include<stdio.h> #define SQR(x) x * x int main() { printf("%d", 225/15*15); } Because of the operator precedence 225/15 executed first and have the result 17 .Then the 17 multiplied by 15 .So the result is 225.So use parenthesis .
Better to use parentheses in the macro so that the macro can be used "normally". You wouldn't normally have to bracket a subexpression so requiring the programmer to remember for SQR that they have to do Code: 225/(SQR(15)) will lead to bugs because you don't remember stuff like this. So define the macro as Code: #define SQR(x) ( (x) * (x) ) so that it can be used normally, i.e. Code: 225/SQR(15) 225/SQR(7+8) etc. The brackets around the individual x's mean you can put subexpressions into SQR. Without them, the second would be substituted as: Code: 225/(7+8*7+8) Of course you always have to be very careful with side effect operators. This won't have the expected result: Code: int i=15; int j=225/SQR(i++); What's i? 16? Nope. No amount of bracketing will fix this, which is why we make macros upper case. And relying on this is definitely a bad idea, cos if some smart alec rewrites SQR as Code: #define SQR(x) (pow((x),2)) then i will be 16 and not 17 as you expected.