C++. Why std::cout << char + int prints int value?

送分小仙女□ 提交于 2021-02-08 21:10:39

问题


Let's say, we have:

char x = 'a';
int y = 1;

So, if you run:

std::cout << x + y;

It prints 98 instead of 'b'. As i see from here <<operator has only int parameter implementation.

From now on i have 2 questions:

  1. After char + int operation what type is returned?
  2. Why there is no char parameter implementation, but std::cout << x still works as expected and prints char value?

回答1:


Thanks to Fefux, Bo Persson and Matti Virkkunen answers are:

  1. From CPP Reference: Implicit conversions:

    arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.

    So return type of x + y is int.

  2. std::cout has a operator<<(char) as a non-member.




回答2:


As you probably know, C++ is backward compatible with C.

Both C & C++ treat chars like ints.

You may consider this a flaw of the language, but on the contrary, this is very handy.

Suppose you want to convert a capital letter to the corresponding small letter. Since any capital letter has an ASCII code 32 below the corresponding small letter, this is as simple as this:

char c = 'A';

std::cout << (char) (c + 32); // output: 'a'

Inversely you can convert from small letter to capital letter:

char c = 'a';

std::cout << (char) (c - 32); // output: 'A'


来源:https://stackoverflow.com/questions/40785687/c-why-stdcout-char-int-prints-int-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!