Re: K&R2 ex 1-8

From: CBFalconer (cbfalconer_at_yahoo.com)
Date: 10/16/04


Date: Fri, 15 Oct 2004 22:34:34 GMT

Merrill & Michele wrote:
>
> The following is my best attempt to solve the exercise in the
> subject line whose simple request is to write a program that
> counts blanks, tabs and newlines.

Which you should specify in the body, since subject lines are not
always visible when reading.

>
> #include <stdio.h>
> int main(int orange, char **apple)
> {
> int c,n1,n2,n3;
> n1=n2=n3=0;
> while((c=getchar()) != EOF)
> {
> if (c=='\n')
> ++n1;
> else if (c=='\t')
> ++n2;
> else if (c==' ')
> ++n3;
> }
> printf("%d %d %d\n",n1,n2,n3);
> return (0);
> }

It appears perfectly satisfactory, except it will needlessly
complain about unused parameters. In place of the obfuscated
parameter names, simply specify they are not supplied by using
void, and you can make the flow clearer by different formatting
(there are no prizes for paucity of blanks):

#include <stdio.h>
int main(void)
{
   int c, n1, n2, n3;

   n1 = n2 = n3 = 0;
   while (EOF != (c = getchar())) {
      if ('\n' == c) ++n1;
      else if ('\t' == c) ++n2;
      else if (' ' == c) ++n3;
   }
   printf("%d %d %d\n", n1, n2, n3);
   return (0);
}

The formatting is purely a matter of style. The practice of
putting the constant first in equality tests makes it easier for
the compiler to pick up errors, because it can now detect the use
of '=' in place of '=='.

-- 
Chuck F (cbfalconer@yahoo.com) (cbfalconer@worldnet.att.net)
   Available for consulting/temporary embedded and systems.
   <http://cbfalconer.home.att.net>  USE worldnet address!


Relevant Pages

  • Ref: Toni Erdmann - GCC difference in size of long
    ... It seems unfair to me that the response Must go to the group you have ... order to compile it. ... error signal caused by a single misplaced int is particularly hard to find. ... You can also specify the architecture of the target. ...
    (alt.os.linux.suse)
  • Re: Wheres the mistake???
    ... Implicit int ... always a good idea to specify the return type of all functions anyhow. ... As I hope you are aware, a prototype is a function ... Dig the even newer still, yet more improved, sig! ...
    (comp.lang.c)
  • Re: standard doubt
    ... that you were told something but disbelieve it. ... that the c standard does not specify the exact size in bytes for its ... implementations\operating systems can have different size for an int. ... be to pick a standard textual representation; ...
    (comp.lang.c)
  • [PATCH] IP1000A: IC Plus update 2006-08-22
    ... int fiber; ... /* Record frame transmit start time (jiffies = Linux ... -/* Specify the number of receive frames transferred via DMA ...
    (Linux-Kernel)
  • [PATCH] IP1000A: IC Plus update
    ... int fiber; ... /* Record frame transmit start time (jiffies = Linux ... -/* Specify the number of receive frames transferred via DMA ...
    (Linux-Kernel)