nhg*_*rif 23
a的值char可以是0-255,其中不同的字符映射到这些值之一.几个数字也存储在顺序'0'通过'9',但他们也没有通常存储为前十个char值.也就是说,该字符'0'的ASCII值不是0.char值0几乎总是\0空字符.
在不知道关于ASCII的任何其他内容的情况下,如何'0'从任何其他数字字符中减去字符将导致原始字符的char值非常简单.
所以,这是简单的数学:
'0' - '0' = 0 // Char value of character 0 minus char value of character 0
// In ASCII, that is equivalent to this:
48 - 48 = 0 // '0' has a value of 48 on ASCII chart
Run Code Online (Sandbox Code Playgroud)
所以,同样地,我可以使用任何char数字进行整数运算...
(('3' - '0') + ('5' - '0') - ('2' - '0')) + '0') = '6'
Run Code Online (Sandbox Code Playgroud)
之间的区别3,5或者2和0ASCII表上正好等于面值我们通常认为,当我们看到数字位数.char '0'从每个中减去它们,将它们一起添加,然后'0'在最后添加一个返回将给我们char值,它表示执行该简单数学运算的结果.
上面的代码片段模拟3 + 5 - 2,但在ASCII中,它实际上是这样做的:
((51 - 48) + (53 - 48) - (50 - 48)) + 48) = 54
Run Code Online (Sandbox Code Playgroud)
因为在ASCII图表上:
0 = 48
2 = 50
3 = 51
5 = 53
6 = 54
Run Code Online (Sandbox Code Playgroud)
在 C 中,+and-运算符将整数提升*1应用于其参数,因此减去(或添加)两个 s 的结果char是int*2。
根据 C 标准:
\n\n\n\n\n5.1.2.3 程序执行
\n\n[...]
\n\n10 示例2 执行片段时
\n\nRun Code Online (Sandbox Code Playgroud)\n\nchar c1, c2;\n/* ... */\nc1 = c1 + c2;\n\xe2\x80\x98\xe2\x80\x98整数提升\xe2\x80\x99\xe2\x80\x99 要求抽象机将每个变量的值提升到
\nint大小,然后将两个相加ints [...]
将其应用于 OP 隐式给出的用例
\n\nchar c = 42;\n... = c - `0`;\nRun Code Online (Sandbox Code Playgroud)\n\n这将导致上述内容与以下内容相同:
\n\n... = (int) c - (int) `0`; /* The second cast is redundant, as per Jens' comment. */ \n ^ ^\n +------ int -----+\nRun Code Online (Sandbox Code Playgroud)\n\n*1:如果运算符参数的级别低于int它们,则将其提升为int. \n
\n*2:char等级低于int。