Always use braces (was: Suggested new C loop syntax)

Dave Decot decot at hpisod2.HP.COM
Thu Jan 5 06:03:49 AEST 1989


> In article <9235 at smoke.BRL.MIL> gwyn at brl.arpa writes:
> >	#include	<stdio.h>
> >	#define	MAGIC	'\0'	/* silly terminating character value */
> >	int			/* returns EOF or MAGIC (why??) */
> >	some_function( void )	/* ANSI C assumed; else delete "void" */
> >		{
> >		int	c;	/* character from standard input */
> >		while ( (c = getchar()) != EOF )
> >			if ( c == MAGIC )
> >				return MAGIC;
> >		return EOF;
> >		}
> 
> #include <stdio.h>
> 
> int f()
>   { int ch;
>     while ((ch = getchar()) != EOF  &&  c)    /*  find EOF or '\0'  */
>     return (ch);
>   }
> 
> Any C programmer will understand how this function works; it takes less
> space, because it is shorter, etc. So: Why is my solution too simple ?

Aside from the fact that it contains a missing semicolon that will cause the
fragment to fail and will not be caught by the compiler, and a use of
two undefined identifiers (c and EOF) that will cause it to generate an
error message, what you meant:

  #include <stdio.h>
  int f()
    { int ch;
      while ((ch = getchar()) != EOF  &&  ch)    /*  find EOF or '\0'  */
  	  ;
      return (ch);
     }

works fine.  However, I would prefer to express the intent and usage
more clearly, as:

    #include <stdio.h>

    /*
       f() discards standard input characters until EOF or null byte is read.
       Returns EOF for EOF; '\0' for null byte.
    */

    int f()
    {
	register int c;		/* input character */

	    while ((c = getchar()) != EOF && c != '\0')
		;

	    return c;
    }

Dave Decot
decot%hpda at hplabs.hp.com



More information about the Comp.lang.c mailing list