I am trying to write this code in code blocks C editor but the output is coming 36 instead of 1.
#include <stdio.h>
#define square(x) x*x
int main()
{
int p=36/square(6);
printf("%d",p);
}
Why is the output 36 instead of 1?
I am trying to write this code in code blocks C editor but the output is coming 36 instead of 1.
#include <stdio.h>
#define square(x) x*x
int main()
{
int p=36/square(6);
printf("%d",p);
}
Why is the output 36 instead of 1?
The problem is that the definition of your macro doesn't have any parentheses in it - and macros aren't 'called', like functions are - they just cause text to be replaced.
So, in your code, the line:
int p=36/square(6);
is replaced with:
int p=36/6*6;
which is evaluated in left-to-right order (as the *
and /
operators have equal precedence), giving, effectively:
int p = (36/6) * 6;
To fix this, add parentheses in your macro definition:
#define square(x) ((x)*(x))
Feel free to ask for further clarification and/or explanation.
The C preprocessor changes the line
int p=36/square(6);
into
int p=36/6*6;
You will get the desired output if your change your preprocesor macro to:
#define square(x) (x*x)
That way, the line will instead be changed to:
int p=36/(6*6);
However, this solution still is not ideal: If you for example write
int p=36/square(6+3);
then the preprocessor will change this to
int p=36/(6+3*6+3);
Therefore, the proper solution would be to change the preprocessor macro to:
#define square(x) ((x)*(x))
That way, the preprocessor will correctly change it to:
int p=36/((6+3)*(6+3));
In this respect, C preprocessor macros behaves very differently from function calls, where the parentheses are not necessary.