Why the output of the below program is 125 and not 5?
#include<stdio.h> #define square(x) x*x int main() { int var; var = 125/square(5); printf("%d",var); return 0; } Why the output of the below program is 125 and not 5?
#include<stdio.h> #define square(x) x*x int main() { int var; var = 125/square(5); printf("%d",var); return 0; } This line:
var = 125/square(5); is expanded into:
var = 125/5*5; which evaluates from left to right to 25*5 and then to 125;
To fix it, parenthesize the argument in the definition of square, like this:
#define square(x) ((x)*(x)) Note also the extra parenthesis around x in order to achieve expected behavior when e.g. 1+2 is passed into square.
Note that var = 125/square(5); becomes var = 125/5*5 when you compile the code.
So the compiler calculates 125/5 before 5*5. The result becomes (125/5)*5 = 125.
Instead of #define square(x) x*x, put #define square(x) (x*x).
Here is your code:
#include<stdio.h> #define square(x) (x*x) int main() { int var; var = 125/square(5); printf("%d",var); return 0; }