-10

I'm coming from high language, PHP js and things. So this seem strange to me.

I'm using either local or online interpreter but I always get this result.

I suppose this result is because '2' is 50 in ASCII and 98 is 'b' but I'm not sure. Also I don't really understand how the conversion work.

The code is here:

#include <iostream>
#include <string>
int main()
{
    std::cout << '1' + 1 << '\n';
    std::cout << '1' + '1' << '\n';
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402

2 Answers2

6

Type char is integral type. Each character maps to an integer value. The value depends on the encoding used which in your case is probably ASCII. So the character '1' probably has an integer value of 49 thus the '1' + '1' expression is equivalent to 49 + 49 and results in 98. Adding integer value of 1 to 49 results in 50. Which is the same as adding integer value of 1 to (a value represented by the) character '1'.

In a nutshell, values are values, whether represented via character literals or integer literals.

Ron
  • 14,674
  • 4
  • 34
  • 47
5

'1' is a char constant with a specific value determined by the encoding used on your system. That encoding might be ASCII, but it might not. When used as an argument to +, it is promoted to an int. So decltype('1') is a char, but decltype('1' + '1') is an int.

On your system, it's clear that '1' has the value 49. That's why'1' + '1' is 98. And therefore '1' + 1 is 50.

Note that in C, '1' is an int type. Arguably that's less confusing than the way C++ has it.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483