for() and while() (was Re: Comparing strings...)

Sudheer Apte sa1z+ at andrew.cmu.edu
Thu Oct 18 06:29:58 AEST 1990


gordon at osiris.cso.uiuc.edu (John Gordon) writes:
>         Also, one other thing: for() and while() loops are essentially 
> identical.  The following loops are exactly the same:
> [ example "for" and "while" loops deleted ]

Yes, but there's one pitfall: the way "continue" is handled.  If you
put a "continue" in a while loop, your incrementing operation at the
end of the loop will never be executed after the "continue" is taken,
making your "while" loop run forever.

Example:

#include <stdio.h>

main()
{
  int i;
  printf("FOR loop: ");
  for (i=0; i<10; i++) {      /* Prints 1 2 3 4 6 7 8 9 */
    if(i==5)
      continue;
    printf(" %d", i);
  }
  printf("\nWHILE loop: ");
  i = 0;
  while (i<10) {
    if (i==5)
      continue;                     /* Bad idea */
    printf(" %d", i); fflush(stdout);
    i++;
  }
  printf("\n");
}


Thanks,
	Sudheer.
------------------------
...{harvard,uunet}!andrew.cmu.edu!sa1z
sa1z%andrew at CMCCVMA



More information about the Comp.lang.c mailing list