字符与整数相加的结果是什么?为何示例代码运行输出103?
Hey there! Let's unpack your questions one by one—this is a super common point of confusion when starting out with C++, so great call asking about it.
char and an int? In C++, a char is actually an integer type under the hood. It stores the ASCII value of the character it represents (for most systems, at least). When you add a char to an int, the compiler does something called integer promotion: the char gets converted to an int first, using its ASCII value. Then the two integers are added together, and the result is an int.
Let's walk through your code line by line:
- You declare
int a = 5—that's straightforward,aholds the integer 5. - You declare
char x = 'b'—on almost all systems, the character 'b' has an ASCII value of 98. Soxis actually storing the integer 98 behind the scenes. - When you do
a + x, that's5 + 98, which equals 103. Since the result is anint,std::coutprints it as a number instead of converting it back to a character.
If you wanted to print the character corresponding to 103 instead, you'd need to cast the result back to char, like this:
std::cout << static_cast<char>(a + x);
That would output 'g', since 103 is the ASCII value for the lowercase 'g'.
内容的提问来源于stack exchange,提问作者tah

