2

When I write the following code the output is 110. Can anyone tell me why I get that value?

#include<iostream>
int main()
{
    std::cout << '9' + '5';
    return 0;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
krishna
  • 147
  • 1
  • 2
  • 9

7 Answers7

4

With ASCII encoding the values of '9' and '5' is 57 and 53 (respectively).

57 + 53 is equal to 110.

What you're adding is the encoded values of the characters, not their digits.

And you get the output 110 (instead of the ASCII character 'n' which have the value 110) because the addition causes the characters to be promoted to int values and the result is an int value that is not converted to a char.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

According to this, the value of 9 is 57, and the value of 5 is 53. 57 + 53 is 110. You're adding those chars, so they get promoted to int, and if you pass an int like this, it gets printed as an int.

What you probably wanted is

std::cout << '9' << '5';

to print 95. Or

std::cout << 9 + 5;

to print 14.

Blaze
  • 16,736
  • 2
  • 25
  • 44
0

The ASCII value of 9 is 57 and of 5 is 53. So 57 + 53 equals 110.

enter image description here

There is no addition for characters, you're adding their ascii value . If you will cast the result to char, the result should be n .

sagi
  • 40,026
  • 6
  • 59
  • 84
0

That's because char's are represented in ASCII(usually as per suggested on the comments).

Literal '9' is 57 and literal '5' is 53. Thus their sum is 110 which is the literal 'm'.

KostasRim
  • 2,053
  • 1
  • 16
  • 32
0

The is no char operator+(char, char), but there is int operator+(int, int). Hence it converts '9' and '5' to ints 57 and 53 respectively first and then does the addition, which result is int 110.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

Based on the original title, it's possible that the OP's intent was to concatenate two string numbers together. If so, this should achieve that.

#include<iostream>
#include<string>
int main()
{
    std::cout << std::string("9") + std::string("5");
    return 0;
}
Tim Randall
  • 4,040
  • 1
  • 17
  • 39
0

With ASCII encoding the values of '9' and '5' is 57 and 53.

57 + 53 is equal to 110.

And the program is returning this value.

If you want program to return the addition of 9 and 5 the you have to write following syntax :-

cout<<9+5;