Printing a char with printf

后端 未结 6 1519
粉色の甜心
粉色の甜心 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:12

    %d prints an integer: it will print the ascii representation of your character. What you need is %c:

    printf("%c", ch);
    

    printf("%d", '\0'); prints the ascii representation of '\0', which is 0 (by escaping 0 you tell the compiler to use the ascii value 0.

    printf("%d", sizeof('\n')); prints 4 because a character literal is an int, in C, and not a char.

提交回复
热议问题