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

后端 未结 6 1165
星月不相逢
星月不相逢 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 12:14

    (char)(i+c) where c is a char gives you a new char with an ascii value equal to (ascii value of c) + i. Since the ascii values of the digits 0-9 are sequential, i+'0' gives you the char corresponding to i, as long as i lies in the appropriate range.

    EDIT : (i+c) is an int, as Jarod42 pointed out. Added a cast to maintain correctness.

提交回复
热议问题