From page 72–73 of Programming: Principles and Practices using C++:
We saw that we couldn’t directly add chars or compare a double to an int. However, C++ provides an indirect way to do both. When needed, a char is converted to an int and an int is converted to a double. For example:
char c = 'x'; int i1 = c; int i2 = 'x';
Here both i1 and i2 get the value 120, which is the integer value of the character 'x' in the most popular 8-bit character set, ASCII. This is a simple and safe way of getting the numeric representation of a character. We call this char-to-int conversion safe because no information is lost; that is, we can copy the resulting int back into a char and get the original value:
char c2 = i1; cout << c << ' << i1 << ' << c2 << '\n';
This will print x 120 x
I do not understand char-to-int conversion. I don't understand the stuff the author has said. Can you please help me?
char
is really nothing more than an integer with a small range (0 to 255 or -128 to 127, depending on ifchar
is unsigned or not), and C++ have many implicit conversions, for example integral promotions. - Some programmer dudechar
is a representation of abyte
that is four bits, giving a binary value between 0000 - 1111, either 0-2555 unsigned, or -128 to 127 signed, as Joachim stated. in programming a charr will be the textual representation, so if you assign the value to anint
, you will get the int value of the char. - JoSSte