I was learning from geeksforgeeks and when i saw this, a thought came in my mind that as getchar()
and other similar functions returns an int(whether due to failure of program or EOF) then why format specifier used is %c
, why not %d(or %i)
.
// Example for getchar() in C
#include <stdio.h>
int main()
{
printf("%c", getchar());
return 0;
}
I know that the character we input in is a character and it is taken by the function getchar()
and we are displaying it using %c
.
But my problem is what's actually happening inside getchar()
and printf()
during the whole process, where getchar()
is returning that integer, where it is getting stored and how the character we inputted is getting displayed by printf()
i.e.what's happening inside printf()
?
I did some research on printf()
implementation and get to know that printf is part of the C standard library
(a.k.a. the libc
) and is a variadic function(printf) but i didn't came to know that what is really happening inside this function and how it knows by format specifier that it has to print character or int?
Please help me learning the whole detailed process which is going on.
The man page for getchar
says the following:
fgetc()
reads the next character from stream and returns it as anunsigned char
cast to anint
, or EOF on end of file or error.
getc()
is equivalent tofgetc()
except that it may be implemented as a macro which evaluates stream more than once.
getchar()
is equivalent togetc(stdin)
.
So let's say you enter the character A
. Assuming your system uses ASCII representation of characters, this character has an ASCII value of 65. So in this case getchar
returns 65 as an int
.
This int
value of 65 returned by getchar
is then passed to printf
as the second argument. The printf
function first looks at the format string and sees the %c
format specifier. The man page for printf
says the following regarding %c
:
If no
l
modifier is present, theint
argument is converted to anunsigned char
, and the resulting character is written.
So printf
reads the next argument as an int
. Since we passed in a int
with value 65, that's what it reads. That value is then cast to an unsigned char
. Since it is still in the rage of that type, the value is still 65. printf
then prints the character for that value. And since 65 is the ASCII value for the character A
, the character A
is what appears.