www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/11/02:00:38

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Hi
Date: Tue, 10 Feb 1998 23:07:06 -0500
Organization: Two pounds of chaos and a pinch of salt.
Lines: 36
Message-ID: <34E123EA.4D2B@cs.com>
References: <34E03363 DOT 1A28E21C AT student DOT unsw DOT edu DOT au> <34E1211E DOT 8F9 AT lan DOT tjhsst DOT edu>
NNTP-Posting-Host: ppp239.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019