This source code is switching on a string in C. How does it do that?

前端 未结 4 815
天命终不由人
天命终不由人 2020-12-04 18:44

I\'m reading through some emulator code and I\'ve countered something truly odd:

switch (reg){
    case \'eax\':
    /* and so on*/
}

How i

4条回答
  •  不知归路
    2020-12-04 19:21

    The code fragment uses an historical oddity called multi-character character constant, also referred to as multi-chars.

    'eax' is an integer constant whose value is implementation defined.

    Here is an interesting page on multi-chars and how they can be used but should not:

    http://www.zipcon.net/~swhite/docs/computers/languages/c_multi-char_const.html


    Looking back further away into the rearview mirror, here is how the original C manual by Dennis Ritchie from the good old days ( https://www.bell-labs.com/usr/dmr/www/cman.pdf ) specified character constants.

    2.3.2 Character constants

    A character constant is 1 or 2 characters enclosed in single quotes ‘‘ ' ’’. Within a character constant a single quote must be preceded by a back-slash ‘‘\’’. Certain non-graphic characters, and ‘‘\’’ itself, may be escaped according to the following table:

        BS \b
        NL \n
        CR \r
        HT \t
        ffffd \ffffd
        \ \\
    

    The escape ‘‘\ffffd’’ consists of the backslash followed by 1, 2, or 3 octal digits which are taken to specify the value of the desired character. A special case of this construction is ‘‘\0’’ (not followed by a digit) which indicates a null character.

    Character constants behave exactly like integers (not, in particular, like objects of character type). In conformity with the addressing structure of the PDP-11, a character constant of length 1 has the code for the given character in the low-order byte and 0 in the high-order byte; a character constant of length 2 has the code for the first character in the low byte and that for the second character in the high-order byte. Character constants with more than one character are inherently machine-dependent and should be avoided.

    The last phrase is all you need to remember about this curious construction: Character constants with more than one character are inherently machine-dependent and should be avoided.

提交回复
热议问题