-
C: getchar
hi,
once again i hit a very simple problem i am unable to resolve. I using Visual Studio 2010, but am compiling for C.
THis:
Code:
char i=45;
while(i=getchar() != EOF)
{
should imo work perfectly (yes, no real code, just to demonstrate the issue), but it doesnt. Getchar() always returns 0x01. Why is that?
This, in contrast, works perfectly fine:
Code:
char i=45;
while(i!= EOF)
{
i=getchar();
Shouldnt an assignment always return the assigned value?
-
Re: C: getchar
When you do:
Code:
while( i = getchar() != EOF )
You are really doing:
Code:
while( i = ( getchar() != EOF ) )
So, it gets the character, compares it against the EOF character. It's most likely not equal to it, and so that boolean will become 1 and get assigned to i. This happens because the != operator has a higher precedence than the assignment operator.
-
Re: C: getchar
There is another problem with your code.
EOF is usually defined as the int -1. If you assign it to a char then the value will be truncated and the test will never be true.
BTW that is the reason why getchar() returns an int and not a char.
Kurt