1

I'm reading through Stroustrup's Principles and Practice using C++ book and while completing an exercise, I noticed cout exhibit some interesting behavior which I don't fully understand.

On line 7 in the code below, I expected that char + char = char, however in this case char + char = int, therefore outputting "113". I understand that the character '0' (48) + 'A' (65) equals 'q' (113) when represented as an int, but what is governing this expression resulting in an int instead of a char?

As the variable my_char contains the same value, I expected both cout statements to output "q".

1  #include <iostream>
2  using namespace std;
3
4  int main() {
5     char my_char = '0' + 'A';   // 'q'
6     cout << my_char   << endl;  // output: "q"
7     cout << '0' + 'A' << endl;  // output: "113" -> why not "q"?
8
9     return 0;
10 }
SassPower
  • 11
  • 2
  • 1
    Marked as a duplicate - in the duplicate question, you can find the type conversion rules for operations between primitive integral types. tl;dr: the smallest type for arithmetic operations is int, so both char operands will be converted to int before performing the + operation. – nneonneo Mar 08 '21 at 04:19

0 Answers0