Is jumping inside loops legal?

A.R. Pruss pruss at ria.ccs.uwo.ca
Fri Aug 3 06:27:19 AEST 1990


I am wondering whether it is legal to jump into a loop, either via
a direct goto, or via a switch-case construct.

What I mean is which (if any) of the following two programs are illegal
and will their functioning be consistent on all legal compilers?

--- begin test1.c ---
#include <stdio.h>

int main()
{
 int j=5;
 switch(getchar())
 {
  case 'y':
  case 'z': puts("y or z depressed!");
	    for(j=0; j<5; j++)     /* here is the loop broken into */
  case 'Z':  puts("A 'z' (case unknown) key was pressed.");
	    break;
 }
 return 0;
}
--end test1.c--

--- begin test2.c ---
#include <stdio.h>

int main()
{
 int x=5;
 goto alpha;
 for(x=0; x<7; x++)   /* and here's the other loop being broken into */
alpha:
  putchar('.');
 return 0;
}
--end test2.c--

They both compile under Turbo C 2.0 (on a PC), MIPS C (under Irix),
gcc -pedantic, as well as passing lint with the exception of test2
having a `warning: statement not reached' (which also appeared under
TC 2.0).  Under Borland's new Turbo C++ 1.0 (on a PC, again), test1
refuses to compile (case not in switch), while test2 does indeed compile.

In all cases where the programs compiled, the output was the same.

pruss at ria.ccs.uwo.ca



More information about the Comp.lang.c mailing list