EOF type not recognized using '!=' ?

support for the ARM toolchain
Post Reply
LeRodeur
Posts: 13
Joined: Tue Jul 31, 2012 2:36 pm

EOF type not recognized using '!=' ?

Post by LeRodeur » Sun Aug 12, 2012 3:27 pm

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!

User avatar
Izhido
Posts: 107
Joined: Fri Oct 19, 2007 10:57 pm
Location: Costa Rica
Contact:

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

Post by Izhido » Wed Aug 15, 2012 8:30 pm

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.

mtheall
Posts: 210
Joined: Thu Feb 03, 2011 10:47 pm

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

Post by mtheall » Wed Aug 15, 2012 10:36 pm

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.

mtheall
Posts: 210
Joined: Thu Feb 03, 2011 10:47 pm

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

Post by mtheall » Wed Aug 15, 2012 10:53 pm

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.

LeRodeur
Posts: 13
Joined: Tue Jul 31, 2012 2:36 pm

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

Post by LeRodeur » Thu Aug 16, 2012 3:58 am

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

Post Reply

Who is online

Users browsing this forum: No registered users and 15 guests