Page 1 of 1

EOF type not recognized using '!=' ?

Posted: Sun Aug 12, 2012 3:27 pm
by LeRodeur
hello,
I don't know if its an inherent problem of gcc, devkitarm or only my lack of knowledge, so if someone could explain me the following thing:
I wrote this function

Code: Select all

inline char fFindC(FILE* file,char c)
{
    char fc=EOF;
    do
    {
        fc=fgetc(file);
    }
    while(fc!=EOF || fc!=c);
    return c;
}
But the loop won't end if EOF is reached, after some tests, I figured that fc!=EOF is always equivalent to true, i had to cast fc to make it work properly

Code: Select all

(s8)fc != EOF 
This problem doesn't happen with == because this code works fine :

Code: Select all

inline char fFindC(FILE* file,char c)
{
    char fc=EOF;
    do
    {
        fc=fgetc(file);
    }
    while(!(fc==EOF || fc==c));
    return c;
}
Thanks!

Re: EOF type not recognized using '!=' ?

Posted: Wed Aug 15, 2012 8:30 pm
by Izhido
Your first while() condition is wrong. You see,

Code: Select all

!(fc==EOF || fc==c)
is not

Code: Select all

(fc!=EOF || fc!=c)
, but rather

Code: Select all

(fc!=EOF && fc!=c)
See http://en.wikipedia.org/wiki/De_Morgan's_laws for an explanation.

Hope that helps.

Re: EOF type not recognized using '!=' ?

Posted: Wed Aug 15, 2012 10:36 pm
by mtheall
Also, fgetc() returns an int, and EOF is an int; its value does not fit inside of char. So

Code: Select all

  char c;
  c = EOF;
  if(c == EOF)
    printf("Hooray! c=%d, EOF=%d\n", c, EOF);
  else
    printf("Nay! c=%d, EOF=%d\n", c, EOF);
Try that out and see what happens. 'c' will get promoted to int for the comparison.

Re: EOF type not recognized using '!=' ?

Posted: Wed Aug 15, 2012 10:53 pm
by mtheall
Point is, the char-to-int promotion that happens here can vary depending on lib/architecture/compiler, (on nds using devkitARM, I get "Nay! c=255, EOF=-1") so in order to maintain portability, you need to fgetc() to an int.

Re: EOF type not recognized using '!=' ?

Posted: Thu Aug 16, 2012 3:58 am
by LeRodeur
For the first thing, my boolean expression was good in my files, I just made a mistake after copy past.. my bad.
Thanks for the explenation, I figured yersteday that fgetc returns int value and not char, and did exactly what you said.
I thought == and != would cast the value as EOF is merely a define of -1, and that the compiler knows exactly the value to compare
But it seems it is not the case