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?
CodePudding user response:
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.