Why doesn't the code below print 16 ,0?
#define SUM 1+3
int main(void) {
printf("%d %d\n", SUM*SUM, 4-SUM);
return 0;
}
Why doesn't the code below print 16 ,0?
#define SUM 1+3
int main(void) {
printf("%d %d\n", SUM*SUM, 4-SUM);
return 0;
}
Because c treats that like x+y, not the result of that addition. (if you want it to treat it like the result, simply put parentheses before and after the expression)
#define SUM (1+3)
int main() {
printf("%d %d\n", SUM*SUM, 4-SUM);
return 0;
}
when sum is replaced to your code it is
#define SUM 1+3
int main(void) {
printf("%d %d\n", 1+3*1+3, 4-1+3);
return 0;
}
where * have higher priority so it makes 1 +(3*1)+3. Add braces to your #define SUM (1+3),then it ll be
printf("%d %d\n", (1+3)*(1+3), 4-(1+3));
You are defining a constant SUM 1+3, so if you write 1+3 for all SUM constant i think you can understand better.
#define SUM 1+3
int main(void) {
printf("%d %d\n", 1+3*1+3, 4-1+3);
return 0;
}
If you calculate according to the process priority, you can understand why.And also if you will use parantheses, you can get an output which you desired;
#define SUM (1+3)
int main(void) {
printf("%d %d\n", SUM*SUM, 4-SUM);
return 0;
}
Because this code is same with this;
#define SUM (1+3)
int main(void) {
printf("%d %d\n", (1+3)*(1+3), 4-(1+3));
return 0;
}