Why this program outputs 225 istead of 1 ?

lionaneesh's Avatar, Join Date: Mar 2010
Invasive contributor
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).
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Precedence is not working as you expect with the MACROS.

Try
Code:
printf("%d", 225/(SQR(15)));
0
karthigayan's Avatar, Join Date: Feb 2010
Go4Expert Member
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 .
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.
Scripting like this