Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Posting-Version: version B 2.10.2 9/5/84; site ur-cvsvax.UUCP
Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!think!harvard!seismo!rochester!ur-cvsvax!bill
From: bill@ur-cvsvax.UUCP (Bill Vaughn)
Newsgroups: net.lang.c
Subject: for <==> while  (an exception)
Message-ID: <200@ur-cvsvax.UUCP>
Date: Wed, 10-Jul-85 19:17:22 EDT
Article-I.D.: ur-cvsva.200
Posted: Wed Jul 10 19:17:22 1985
Date-Received: Sat, 13-Jul-85 12:07:11 EDT
Distribution: net
Organization: Center for Visual Science, U. of Rochester
Lines: 75

(Stop me if you've seen this before.)

Section 3.5 of K&R (p. 56) states that the 'for' loop and 'while' loop
can be made equivalent i.e.

					expr1;
for (expr1; expr2; expr3)		while (expr2) {
	statement		<==>		statement
						expr3;
					}

Well ... almost.
As the following program demonstrates there is at least one exception:
If 'statement' contains a 'continue' statement, things may go awry.

Are there any other exceptions?

/*---------------------------------------------------------------------------
 * A program to show a problem with the
 * equivalence between for and while loops.
 */

#include 
#include 

int i;

main()
{
	int message(), stop();

	signal(SIGALRM, message);
	signal(SIGINT, stop);

	/*
	 * Here's the for loop ...
	 */
	for (i=0; i<10; i++) {
		if (i > 0)
			continue;
	}

	printf("%d\n",i);
	printf("Hanging ...");
	fflush(stdout);
	alarm(5);

	/*
	 * Here's the equivalent while loop ..
	 * See K&R p. 56.
	 */
	i=0;
	while (i<10) {
		if (i > 0)
			continue;
		i++;
	}
}

stop()
{
	printf("\n%d\n",i);
	printf("The 'continue' statement 'breaks' the for/while equivalence.\n");
	exit(0);
}

message()
{
	printf("\t\tHit your interrupt key to stop this thing.\n");
}

/*----------------------------------------------------------------------*/

Bill Vaughn
{allegra,seismo,decvax}!rochester!ur-cvsvax!bill