Code Doodles #2 – the quirky switch

According to grammar rules defined by the C++ standard (and C as well) the following code is valid:

switch(i) i++;

This peculiar statement has no effect, other than confusing the potential reader and possibly counting as an assertion that increment is indeed possible for i, although the point of using such a switch statement for static assertions eludes me.

The rules that allow this:
switch statement:

§6.4 Selection statements
switch ( condition ) statement

where statements may be one of the following:

§6 Statements
statement:
labeled-statement
attribute-specifier-seqopt expression-statement
attribute-specifier-seqopt compound-statement
attribute-specifier-seqopt selection-statement
attribute-specifier-seqopt iteration-statement
attribute-specifier-seqopt jump-statement
declaration-statement
attribute-specifier-seqopt try-block

Where our i++ is such a statement.

In the same vein the following code compiles:

#include <iostream>
#include <iomanip>
 
int main()
{
	int i = 0;
 
	switch(i){
	i++;
	case 0: i++; break;
	default:;
	}
 
	std::cout << i << std::endl;
 
	return 0;
}

As expected, the first i++ is not – and, in fact, cannot be – executed, because there are no labeled statements associated with it.

It could probably be called an oversight of the standard, but it’s hardly a popular problem, so I doubt there’s reason to complicate parsing rules even more. And if you ever see this during a code review, kill it with fire, as quaint as it is.

Leave a Reply

Your email address will not be published.