Mail Archives: djgpp/1998/02/11/02:00:38
Eamon Walsh wrote:
>
> Charbel Sadaka wrote:
> > while (ch=getchar( ) != EOF) {
> > count++
>
> Besides the fact that EOF is control Z in dos, not control D, this code
> won't work because the != operator has higher precedence than the =
> (assignment) operator. So what the code in the while parentheses says
> is "if you entered EOF then store false in ch, else store true". You
> can fix this using parentheses: (ch = getchar()) != EOF)
The really odd part is that, while the expression is logically
incorrect, it still works as desired, because when false (0) is assigned
to ch, the while loop terminates. It just happens that ch is not being
assigned the character that was read from the file.
There's another potential bug: if ch is declared as a char instead of
an int (the type returned by getchar()), it's possible for a valid input
character to be interpreted as an EOF. Specifically, the default char
type in DJGPP is 'signed char', and ASCII code 255 (a valid character in
a binary file) is the same as -1, the EOF character, for a signed char.
Even if the default were 'unsigned char', its range (0-255) is
incompatible with EOF, which is -1.
Using the '-Wall' parameter with gcc would have revealed all these
errors. I cannot stress enough how important it is to use '-Wall' when
compiling all programs!
--
---------------------------------------------------------------------
| John M. Aldrich | "Always listen to experts. They'll |
| aka Fighteer I | tell you what can't be done, and why.|
| mailto:fighteer AT cs DOT com | Then do it." |
| http://www.cs.com/fighteer/| - Lazarus Long |
---------------------------------------------------------------------
- Raw text -