Why does adding a '0' to an int digit allow conversion to a char?

后端 未结 6 1154
星月不相逢
星月不相逢 2020-12-31 11:28

I\'ve seen examples of this all over the place:

int i = 2;
char c = i + \'0\';
string s;
s += char(i + \'0\');

However, I have not yet seen

6条回答
  •  梦毁少年i
    2020-12-31 12:08

    The C++ standard says, in its [lex.charset] section “the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous” (quoted from draft N4659).

    Thus, the value of '1' is '0'+1, and the value of '2' is one more than that, which is '0'+2, and so on. If n has a value from 0 to 9, then '0'+n is the value for the corresponding character from '0' to '9'.

    (Unlike the earlier answers, this answer does not assume ASCII and shows how the property derives from the C++ standard.)

提交回复
热议问题