0

I am new to C (coming previously from Python). I am confused over this part of code:

#include <stdio.h>
#define square(x) x*x
int main()
{
    int x = 36/square(6);
    printf("%d", x);
    return 0;
}

I don't know why macro square(x) is not producing output 1 and why is it printing 36? Can you shed some light on this?

Arnav
  • 163
  • 1
  • 8

1 Answers1

4

You need to wrap the macro in parentheses, like this:

#define square(x) (x*x)

The way you've written it, 36/square(6) expands to 36/6*6, which is evaluated as (36/6)*6, or 36.

With parentheses, it will correctly be evaluated as 36/(6*6), or 1.

sj95126
  • 6,520
  • 2
  • 15
  • 34
  • This macro is still wrong. `square(1+1)` will be 3 instead of 4. And possibly, `int i=1; int result=square(i++);` is undefined behavior (at least in C++). Just use a function, not a macro at all. `constexpr` if you can (C++). – Thomas Weller Jul 19 '23 at 07:46
  • See also: https://stackoverflow.com/a/76719135/480982 – Thomas Weller Jul 19 '23 at 08:05