Switch case common code (long)

ruff at cisden.UUCP ruff at cisden.UUCP
Fri Jun 6 08:07:50 AEST 1986


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



More information about the Comp.lang.c mailing list