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 eg 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.