-
November 9th, 2012, 01:27 AM
#1
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?
-
November 9th, 2012, 02:20 AM
#2
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.
-
November 9th, 2012, 05:51 AM
#3
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|