4
#include <iostream>
#include <string>

int main() { 
    char s2;
    s2 = '1' - '0';
    std::cout << s2;
    std::cout << std::endl;
    std::cout << '1' - '0';
    std::cin >> s2;
}

The output produced is:

☺
1

My question is, why are the two lines different? I expected and wanted both results to be 1. By my understanding they should be the same but that is obviously wrong, could somebody please explain this to me? Thank you

197
  • 351
  • 3
  • 12

3 Answers3

8

why are the two lines different?

The type of the first expression (s2) is char. The type of the second ('1' - '0') is int.

This is why they are rendered differently even though they have the same numeric value, 1. The first is displayed as ASCII 1, whereas the second is displayed as the number 1.

If you are wondering why '1' - '0' gives an int, see Addition of two chars produces int

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

s2 is char, '1'-'0' is int.

so it types the char value of 1 which is the smile, and 1 for the int value.

Dani
  • 14,639
  • 11
  • 62
  • 110
1

Type of s2 is char, std::cout << s2 will call std::ostream::operator<<(char) to echo a ASCII character 1 (smile);

'1' - '0' is interpreted as a int value, so std::ostream::operator<<(int) will be called and integer 1 will be printed.

Feng Qin
  • 21
  • 3