Print decimal value of a char

后端 未结 5 1031
春和景丽
春和景丽 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:16

    C11 $6.4.4.4 (Character constants):

    A multi-char always resolves to an int, but that the exact value is “implementation-dependent”. That is, different compilers may resolve the same multi-char to different integers. This is a portability problem, and it is one of the reasons multi-chars are discouraged.

    It means int ch = 'AB'; is ok for int type.But, If it were declared as type char, the second byte would not be retained.

    So use

    char ch = 'A';
    

    instead of

    char ch = 'AB';
    

    and use %c format specifier for char type.

    printf("ch is %c\n",ch);
    

提交回复
热议问题