int c;
while ((c = getchar()) != EOF)

In the above code, why it is prefereble to use variable 'c' as integer datatype rather than character datatype eventhough we are assigning characters to 'c' ?

Can any one explain clearly??

getchar returns int not char. You need to store the value as an int to test against EOF because EOF is defined as an int (normally with the value of -1).

If you converted the value of getchar to a char before comparing to EOF you would have trouble in 1 of 2 ways

On systems with default signed char you would be unable to distinguish between the character value 0xFF and EOF because 0xFF is -1 in 8 bits.

On systems with default unsigned char you would never see the EOF because when getchar returned EOF (-1 in 16 or 32 bits 0xFFFFFFFF) it would be truncated to 0xFF. Then 0xFF would be converted to int for the comparison resulting in the value 255 and 255 is != -1 so you would loop forever.

It is more than perferable for c to be an int, it is essential.

"On systems with default signed char you would be unable to distinguish between the character value 0xFF and EOF because 0xFF is -1 in 8 bits"...

But which character has the ASCII value of 0XFF is -1, im struggling with this question only.

> But which character has the ASCII value of 0XFF is -1

The stream you are reading is not necessarily textual. getchar() must read any data.

0xff in the extended ascii table is displayed as 'ÿ'. In some cases you can enter it from the keyboard by holding dowm the Alt key and entering 255 on the numeric key pad.

thanq friends..i got ur points :)

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.