What is the result of adding a char and an int?

  • A+
Category:Languages

When executing this code:

#include <iostream>  int main(){     int a = 5;    char x = 'b';     std::cout << "The Answer is" << std::endl;    std::cout << a+x; } 

I get the output:

The Answer is
103

Why does this happen?


When you add a char to an int, the r-value created is promoted to an int. Therefore what is printed is the int equivalent to the sum of the (usually) ASCII value + the int.

The ASCII value of 'b' is 'b' == 98. Therefore 98 + 5 == 103 (integer).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: