-3

I have a doubt in the output of a code. The code uses preprocessors of c language. The code is given below,

#include <stdio.h>
#define sqr(x) x*x

int main() {

    int x = 16/sqr(4);
    printf("%d", x);
}

The result of sqr(4) is equal to 16. So, the value in x must be 1 (16/16=1). But if I print the value of x, the output is 16. Please explain me why this is happening.

I am attaching the screenshot of output pane. Output Window

Hem Bhagat
  • 323
  • 3
  • 12

4 Answers4

1

After macro replaces your expression, it becomes int x = 16/4*4 and is evaluated accordingly. i.e. (16/4)*4 which is 16.

sqr(x) doesn't calculate 4*4, it is not a function.

Breakpoint
  • 428
  • 6
  • 19
1

In C, macros are filled into your code upon compilation. Let's consider what happens in your case:

Your macro is:

#define sqr(x) x*x

When it gets filled into this:

int x = 16/sqr(4);

You would get:

int x = 16/4*4;

Operator precedence being equal for / and *, this gets evaluated as (16/4)*4 = 16, that is, from left to right.

However, if your macro were this:

#define sqr(x) (x*x)

then you would get:

int x = 16/(4*4);

... and that reduces to 1.

However, when the argument for your macro is more complex than a simple number, e.g. 2+3, it would still go wrong. A better macro is:

#define sqr(x) ((x)*(x))
Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37
0

You are actually doing 16/4*4 which is in fact 16.

You can change your define to

#define sqr(x) (x*x)

Now you will be doing 16/(4*4).

0

It is expanded to

int x = 16/4*4;

Something like

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

would be more safe, precedence and associativity-wise, still works poorly in expressions like sqr(a++). Inline functions are simpler to use in this context.

bipll
  • 11,747
  • 1
  • 18
  • 32