为什么字母“ A”要和0x41比较?

我查看了一些 C + + 代码,发现了以下结构:

if('A' == 0x41) {
// ...
} else if('A' == 0xc1) {
// ...
} else {
// ...
}

我收到 视觉工作室的警告说:

警告 C4127条件表达式为常数。

Visual Studio 显然是正确的——当然“ A”被定义为0x41。既然三个分支中有两个是死代码,那么作者为什么要编写这段代码呢?

8394 次浏览

0xc1 is the EBCDIC character set code for A. The author is testing for such a machine.

http://www.ibm.com/support/knowledgecenter/en/SSGH4D_15.1.3/com.ibm.xlf1513.aix.doc/language_ref/asciit.html

At first sight might look like that is dead code but 'A' == 0x41 not always will return true..

what the developer tried to do here is lazily find what encoding is the machine implementing ASCII or any variant of EBCDIC

as @Richard suggested Capital a is mapped to 0xc1 in the International - Extended Binary Coded Decimal Interchange Code see table below in the 2 branch of the if else...

enter image description here

another different value could be found by ASCII for exmaple:

enter image description here

he could as well have done:

if('p' == 0x70) {
// ...
} else if('p' == 0x97) {
//...
}