Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!burl!ulysses!gamma!epsilon!zeta!sabre!petrus!bellcore!decvax!decwrl!pyramid!pesnta!hplabs!hao!nbires!boulder!cisden!ruff From: ruff@cisden.UUCP Newsgroups: net.lang.c Subject: Switch case common code (long) Message-ID: <605@cisden.UUCP> Date: Thu, 5-Jun-86 18:07:50 EDT Article-I.D.: cisden.605 Posted: Thu Jun 5 18:07:50 1986 Date-Received: Mon, 9-Jun-86 01:12:01 EDT Reply-To: ruff@cisden.UUCP (Craig Ruff) Organization: ConTel Information Systems, Denver Lines: 112 This problem was floating around a while ago, but I thought this might be an interesting revisitation. Given the following bit of code: switch (switch_variable) { case a: ... ... common_code_for_a_and_b break; case b: ... ... common_code_for_a_and_b break; case c: ... ... break; } The problem was to write (for whatever reason) the common_code_for_a_and_b exactly once in the source, and not as a function. Since the definition of the language does not require a compound statement after the switch, you could write it in several hideous ways... switch (switch_variable) for (; FALSE; common_code_for_a_and_b) { case a: ... ... continue; case b: ... ... continue; case c: ... ... break; } or switch (switch_variable) { while (TRUE) { case a: ... ... break; /* From while only! */ case b: ... ... break; /* From while only! */ } common_code_for_a_and_b; break; /* From switch! */ case c: ... ... break; /* From switch! */ } Of course, there are some restrictions on the type of statements in the for statement, but you could implement ifs and other types with the setjmp/longjmp facility as in that prime finding program that showed up on the net some time ago... Yes, I know that you really shouldn't do anything this way, but it was fun! There is no restriction on where the case labels reside within the scope of the switch statement. Of course, with an auxillary variable and the for, you could implement the common_code_comes_first variation. flag = FALSE; switch (switch_variable) for (; TRUE; common_code_for_a_and_b, flag = TRUE) { case a: if (flag == FALSE) continue; if (switch_variable != a) { ... ... break; } case b: if (flag == FALSE) continue; if (switch_variable != b) { ... ... break; } break; /* To separate from non-common code cases */ case c: ... ... break; } These constructs would be excellent candidates for the obfuscated C contest. Craig Ruff hao!cisden!ruff