"for" loops (was Re: C++ vs. Modula2)

Guy Harris guy at auspex.UUCP
Sat Jan 28 15:23:12 AEST 1989


>Actually, C's "for" can be duplicated EXACTLY by C's "do ... while"
>loops.

No, they can't.

	for (i = 0; i < N; i++)	/* N is a *variable* here */
		stuff;

isn't duplicated by

	i = 0;
	do
		stuff;
	while (++i < N);

because, if N is 0, the first loop will be executed 0 times and the
second loop will be executed 1 time.  It *is* duplicated by

	i = 0;
	while (i < N) {
		stuff;
		i++;
	}

as long as "stuff" doesn't include a "continue" (see p. 60 of K&R
Second Edition; there's probably similar stuff somewhere in the First
Edition).

>These two iterations are indistinguishable from one another.  The "for" term
>in C is totally superfluous and is only included because it makes it look like
>languages that have a more "for"-ish "for" statement, like Pascal or Modula.

Well, to quote something else from p. 60:

	   The "for" is preferable when there is a simple initialization
	since it keeps the loop control statements close together and
	visible at the top of the loop.

Whether you agree with that opinion or not is your business; however, it
seems the reason "for" was included wasn't solely to "make it look like
languages that have a more 'for'-ish 'for' statement", but because DMR
felt the "for" statement had merits of its own.



More information about the Comp.lang.c mailing list