for <==> while (an exception)
Bill Vaughn
bill at ur-cvsvax.UUCP
Thu Jul 11 09:17:22 AEST 1985
(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 <stdio.h>
#include <signal.h>
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
More information about the Comp.lang.c
mailing list