Printing a char with printf

后端 未结 6 1498
粉色の甜心
粉色の甜心 2021-01-01 11:36

Are both these codes the same

char ch = \'a\';
printf(\"%d\", ch);

Will it print a garbage value?

I am confused about this

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 12:10

    This is supposed to print the ASCII value of the character, as %d is the escape sequence for an integer. So the value given as argument of printf is taken as integer when printed.

    char ch = 'a';
    printf("%d", ch);
    

    Same holds for printf("%d", '\0');, where the NULL character is interpreted as the 0 integer.

    Finally, sizeof('\n') is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.

    It all depends on the interpretation you give to the bytes.

提交回复
热议问题