1
#include<stdio.h>

#define sqr(x) x*x

int main()    
{    
    int a = 16/sqr(4);

    printf("%d", a);    
}

if I am not wrong the output should be 1 as ,a = 16/sqr(4) gives 16/16 => 1

but the output is 16

this is happening only when I take division operator(/) ,I am getting correct output when using other operators

may I know the reason? .. and thank you

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40

3 Answers3

4

16 / 4 * 4 is (16 / 4) * 4 = 16

Moral: always take care with macros. In your case you should enclose in parenthesis:

#define sqr(x) ((x)*(x))

There are still problems with this macro as it evaluates the argument twice.

For instance:

int read_int();

int a = 16 / sqr(read_int());

Will unexpectedly evaluate read_int() twice as it expands to:

int a = 16 / ((read_int() * (read_int());

The advice would be to use functions for this. Make it inline to give the compiler better chances to optimize it.

bolov
  • 72,283
  • 15
  • 145
  • 224
2
a = 16/sqr(4);

Expanded the above expression gives:

a = 16 / 4 * 4

Which is 16 based on normal mathematical order of operations.

That's why macros should always be enclosed in parentheses:

#define sqr(x) ((x) * (x))
kaylum
  • 13,833
  • 2
  • 22
  • 31
0

Are you trying to make a function definiton? If yes, then i don't think it should be on a #define. Instead, make a function sqr(x). Here's how:

#include <stdio.h>

int sqr(int x)
{
    return x*x;
}

int main()
{
    int a = 16/sqr(4);

    printf("%d", a);
}

And you'll get the result 1.

Edit: but anyway, you've already get the solution with macros. This is just another way to do what you want.

Nix
  • 13
  • 4