Question about C?

P

Pravin Shetty

Hi to all,

Q)
main()
{
int c;
c=getchar();

while(c!=EOF)
{
putchar(c);
c=getchar();
}
}

: - why instead of declaring c as a char is declaered as an int?
why EOF is defined as an int in <stdio.h>
 
M

Mike Wahler

Pravin Shetty said:
Hi to all,

Q)
main()
{
int c;
c=getchar();

while(c!=EOF)
{
putchar(c);
c=getchar();
}
}

: - why instead of declaring c as a char is declaered as an int?

Because 'getchar()' returns type 'int'.

why EOF is defined as an int in <stdio.h>

So that it can be distinguished from any possible 'char' value.

-Mike
 
B

Ben Pfaff

Hi to all,

Q)
main()
{
int c;
c=getchar();

while(c!=EOF)
{
putchar(c);
c=getchar();
}
}

: - why instead of declaring c as a char is declaered as an int?

It's in the FAQ.

12.1: What's wrong with this code?

char c;
while((c = getchar()) != EOF) ...

A: For one thing, the variable to hold getchar's return value must
be an int. getchar() can return all possible character values,
as well as EOF. By squeezing getchar's return value into a
char, either a normal character might be misinterpreted as EOF,
or the EOF might be altered (particularly if type char is
unsigned) and so never seen.

References: K&R1 Sec. 1.5 p. 14; K&R2 Sec. 1.5.1 p. 16; ISO
Sec. 6.1.2.5, Sec. 7.9.1, Sec. 7.9.7.5; H&S Sec. 5.1.3 p. 116,
Sec. 15.1, Sec. 15.6; CT&P Sec. 5.1 p. 70; PCS Sec. 11 p. 157.
why EOF is defined as an int in <stdio.h>

I think it follows from the above.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top