Milan Shah
Milan Shah

Reputation: 111

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?

Upvotes: 0

Views: 1066

Answers (2)

Bathsheba
Bathsheba

Reputation: 234875

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.

Upvotes: 11

Green Cloak Guy
Green Cloak Guy

Reputation: 24711

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.

Upvotes: 3

Related Questions