1

Is it for the same reason as char + char = int? Why? ?

I got different results on this source code by different compilers

#include <stdio.h>
int main() {
    char a = 100, b = 100;
    printf("%d\n", a + b);
    scanf("%d%d", &a, &b);
    printf("%d\n", a + b);
}
Antithesis
  • 13
  • 2

1 Answers1

1

You get different results because scanf("%d%d", &a, &b) is incorrect. For each %d, scanf expects the address of an int object, but you provided the addresses of char objects. This results in (dangerous) undefined behaviour.

For char objects, use the following:

scanf("%hhd%hhd", &a, &b)    // In a environment with signed chars
  -or-
scanf("%hhu%hhu", &a, &b)    // In a environment with unsigned chars
ikegami
  • 367,544
  • 15
  • 269
  • 518