简体   繁体   中英

Why does `printf(“%c”, 5)` print a vertical bar?

Here is the code

#include <stdio.h>

int main()
{
    printf ("\t%d\n",printf("MILAN"));
    printf ("\t%c",printf("MILAN"));
}

Here is the output

$gcc -o main *.c
$main

MILAN 5

MILAN |

Now the question is

Why printf return | when we are printing characters (formatter as %c) ?

What is the relation between 5 and | here?

Your question really boils down to the behaviour of printf("%c", 5); .

The actual output is a function of the character encoding used by your platform. If it's ASCII (very common) then it will output the control character ENQ . What you actually get as an output will depend on your command shell, and a vertical bar is not an unreasonable choice.

printf returns the number of characters printed . In this case, that number is 5, as you've seen. The second print you're doing tries to typecast that int to a char , which C lets you do because it's C. On your computer, it shows up as a |. I see it rendered as a blank character. As @Bathsheba says, the integer 5 corresponds to a control character in ASCII, and the rendering for those is system-dependent.

Here's an ascii table, if you're curious about other numbers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM