Hi,

I have this doubt i have read that "We must declare c to be a type big enough to hold any value that getchar returns We can't use char since c must be big enough to hold EOF in addition to any possible char. Therefore we use int." it means that char value can be greater than 127 or 255 depending on the machine. Then there should not be any statement like

char ch;
scanf("%c",ch);

since char cannot accomodate all the characters. Please help me to understand.

Thanks in advance

No a char value can not be larger than what fits inside a char. However what getchar returns does not have to be a char value. It could also be EOF.

Except for the missing &, your scanf line is perfectly fine.

When scanf reaches the end of file (or any unexpected input), it will return a number that is less than the expected one. It will not write anything into the given pointers. Therefore there is no need for an EOF value with scanf.

Thank you very much for the reply. Sorry for the mistake of scanf. Just one more doubt i have written code like this

#include <stdio.h>
int main(void)
{
 int ch;
 ch = getchar();
 putchar(ch);
}

if you see the output if i enter any value bigger than 1 character it displays only the first character.
Like input 567
Output is 5.

Can you please tell me one example where it will cross the character range since EOF -1 is also captured in char data type. I am confused.

EOF is not captured in the char data type. EOF is represented as an int with the value -1. Now you say "why can't we just use a char with the value -1 - isn't that the same thing?". And the answer is: because, depending on the encoding, there are already 256 valid character values. So the char -1 (or 255 depending on whether char is signed or unsigned) already represents a valid character - it can't also represent EOF.

What getchar does is it represent the 255 valid character values as ints from 0 to 255 and it represents EOF as -1. So 255 and -1 are two very different results.

Wow great explanation thankyou very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.