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;
}
  • 4
    `#define SUM 1+3` ==> `#define SUM (1+3)` otherwise `SUM*SUM` becomes `1+3*1+3` which is `1+(3*1)+3` or `7`. General rule is: when it comes to `#define`s **use and abuse parenthesis**. – pmg Jan 28 '22 at 13:07

3 Answers3

1

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;
}
Ilai K
  • 126
  • 4
1

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));
Tomáš Šturm
  • 489
  • 4
  • 8
1

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;
}
Ogün Birinci
  • 598
  • 3
  • 11