Notes

2014-09-03

While hacking on my text editor I discovered a fun idiom. Often, in a switch statement you have two cases that are very similar except in one or two points. In that situation it would be poor style to copy the big chunk of code that is common to the two cases, instead, you can use the following neat trick.

switch(type) {
	...
case X:
	isx = 1;
if (0) {
case Y:
	isx = 0;
}
	common code;
	...
	break;
}

The line isx = 0; will only be executed when the type is Y because of the guard. This is very similar and sort of dual to Duff's device. For additional fun, the braces of if (0) can be removed!