Why is %c used in C?

前端 未结 6 1037
误落风尘
误落风尘 2021-01-05 10:55

According to K&R C section 1.6, a char is a type of integer. So why do we need %c. And why can\'t we use %d for everything?

相关标签:
6条回答
  • 2021-01-05 11:10

    Roughly speaking, %c prints the ASCII representation of the character. %d prints its decimal value.

    0 讨论(0)
  • 2021-01-05 11:11

    Because %d will print the numeric character code of the char:

    printf("%d", 'a');
    

    prints 97 (on an ASCII system), while

    printf("%c", 'a');
    

    prints a.

    0 讨论(0)
  • 2021-01-05 11:11

    While it's an integer, the %c interprets its numeric value as a character value for display. For instance for the character a:

    If you used %d you'd get an integer, e.g., 97, the internal representation of the character a

    vs

    using %c to display the character 'a' itself (if using ASCII)

    I.e., it's a matter of internal representation vs interpretation for external purposes (such as with printf)

    0 讨论(0)
  • 2021-01-05 11:24

    If you use %c, you'll print (or scan) a character, or char. If you use %d, you'll print (or scan) an integer.

    printf("%d", 0x70);
    

    How will the machine would know that you want to output a character, not its equivalent ASCII value?

    0 讨论(0)
  • 2021-01-05 11:24

    %d is used to print decimal(integer) number ,while %c is used to print character.If you try to print a character with %d format the computer will print the ASCII code of the character.

    0 讨论(0)
  • 2021-01-05 11:31

    %d think char is 32bit and print it like a integer, but %c convert int value of char to ascii character then print it.

    0 讨论(0)
提交回复
热议问题