A while ago I was digging deep into a C++ project, chasing an obscure bug. Neither the project in question nor the bug are important here. What’s important is that I’ve stumbled upon a weird syntax, that seemed wrong. What’s weird is that this block of code worked flawlessly, unlike some other parts of the project.

Turns out you can have blocks of code inside a switch statement spilling between cases. Let me show you a simplified example:

void f(int a, int b)
{
	switch(a) {
	case 1:
		if (b > 0) {
	case 2:
			printf("a=%d b=%d\n", a, b);
		}
	}
}

No way!

Yep. That works. The if is taken into account only when a is 1, thus it prints only if b is greater than 0. However, if a is 2, the function always prints the values of a and b.

I’m not really sure whether this behavior has been allowed on purpose. It was more likely never thought of given that as stated in K&R (page 53):

[..] cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape

And really, they’re just goto labels. In C switch is just a syntax sugar for a branch table . No wonder that the condition should always be an integer. The execution should jump to the address of the given index (i.e. case condition) in the table. Once jumped, it always moves on and falls through cases.

Y tho?

When is it a good idea to do that, you ask? Never. Please, don’t. I cannot think of a single case (pun not intended) where this would make the code more readable or less error-prone. Using this approach would be objectively worse in every aspect. Besides, this doesn’t even work in “modern” C-style languages, where switch statements are not that simple, thankfully.

Why am I showing you this, then? Well, I find it hilarious and had a hard time explaining it to a friend with words. It’s nowhere trivial to find an example, either. But now I have it written and will be able to explain that insanity better while in a bar. I’m fun at parties.