Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Why this program outputs 225 istead of 1 ? (http://www.go4expert.com/forums/program-outputs-225-istead-1-t21589/)

 lionaneesh 30Mar2010 21:42

Why this program outputs 225 istead of 1 ?

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).

 shabbir 31Mar2010 07:32

Re: Why this program outputs 225 istead of 1 ?

Precedence is not working as you expect with the MACROS.

Try
Code:

`printf("%d", 225/(SQR(15)));`

 karthigayan 31Mar2010 09:27

Re: Why this program outputs 225 istead of 1 ?

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 .

 xpi0t0s 31Mar2010 12:10

Re: Why this program outputs 225 istead of 1 ?

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.

 All times are GMT +5.5. The time now is 20:42.