For vs while (was Re: Comparing strings...)

T.L.Goodwin tlg at ukc.ac.uk
Wed Oct 17 21:14:44 AEST 1990


In article <1990Oct17.030157.460 at ux1.cso.uiuc.edu> 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:
>
>#1) 	    for(i = 0; i < 100; i++)
>	    {
>		body of loop
>	    }
>
>#2) 	   i = 0;
>	   while(i < 100)
>	   {
>	     body of loop
>	     i++;
>	   }

Almost, but not quite.  If the body of the loop contains a "continue",
then the second example becomes an infinite loop (other changes to i
and "break"s notwithstanding), since the increment is never reached.

John is not alone: this equivalence is wrongly claimed in Steve
Bourne's book "The UNIX System", and also K&R (2, I haven't got a copy
of 1 handy), although Bjarne Stroustrup gets it right in the C++
reference manual.

Regards,

Tim Goodwin.



More information about the Comp.lang.c mailing list