pruss@ria.ccs.uwo.ca (A.R. Pruss) (08/03/90)
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@ria.ccs.uwo.ca
steve@taumet.com (Stephen Clamage) (08/04/90)
pruss@ria.ccs.uwo.ca (A.R. Pruss) writes: >I am wondering whether it is legal to jump into a loop, either via >a direct goto, or via a switch-case construct. Perfectly legal in ANSI C, and there is an example comparable to yours (except for one point) in section 3.6.6.1 The goto statement. The point to watch is that the initializer of the for loop will not be executed when you jump into the middle, so if you have goto middle; for(i = 0; i < max; i++) { ... middle: ... } there is no telling how many iterations will be performed. "Legal" is not the same as "good", however, and such code is hard to read, hard to maintain, and may prevent a the compiler from generating good code. It is worth your time to study your algorithm and code it in a more straightforward way. When I encounter such code written by others, I usually find that recoding it without tricks results in source code that is shorter and easier to understand, and in object code which is smaller and faster. -- Steve Clamage, TauMetric Corp, steve@taumet.com