Print decimal value of a char

后端 未结 5 1053
春和景丽
春和景丽 2021-01-27 10:34

Program to print decimal value of a char:

#include

int main(void){

  char ch = \'AB\';
  printf(\"ch is %d\\n\",ch);

}

Why i

5条回答
  •  醉酒成梦
    2021-01-27 11:14

    Because 'AB' is a multi character constant whose value is implementation defined, whether it's 66 or not is "not predictable" in principle and in practice though predictable is not the same across different implementations.

    Normally, you only use a single character in the middle of single quotes. If you use multiple characters,

    1. The compiler should warn about it.
    2. The value if the corresponding int is "not predictable" because it's implementation defined. Of course, given an implementation we hope that a multi character constant does always have the same value.

    If you have used gcc, then this is what happens according to this source

    The compiler evaluates a multi-character character constant a character at a time, shifting the previous value left by the number of bits per target character, and then or-ing in the bit-pattern of the new character truncated to the width of a target character. The final bit-pattern is given type int, and is therefore signed, regardless of whether single characters are signed or not. If there are more characters in the constant than would fit in the target int the compiler issues a warning, and the excess leading characters are ignored.

    For example, 'ab' for a target with an 8-bit char would be interpreted as ‘(int) ((unsigned char) 'a' * 256 + (unsigned char) 'b')’, and '\234a' as ‘(int) ((unsigned char) '\234' * 256 + (unsigned char) 'a')

提交回复
热议问题