C abuse of the week

Feb 21, 2012 11:53


I continue to be amazed at the number of bizarre things you can arrange to do using the C preprocessor, the switch statement, and a strong stomach. I've previously used the combination to implement coroutines, of course, and also a modified version of for which performs its test after the loop body rather than before it.

Chris mentioned to me this morning the fact that you could write this sort of thing:

switch (get_value()) case 1: case 2: case 3: do_stuff();

which has the handy effect of calling get_value() only once and then testing its return value against several possibilities (though they're constrained to be compile-time constant integers). But of course it's hopelessly ugly, so he challenged me to wrap it up in a macro or two. (Not that that stops it being ugly, exactly. But differently ugly. :-)

The obvious solution seemed to me to be this:

#define IF_IN_LIST(expr,list) switch (expr) case list:
#define OR : case

which then lets you write compound statements that only look slightly un-C-ish:

IF_IN_LIST(get_value(), 1 OR 2 OR 3)
do_stuff();

But then I realised that if you dangle a few more oddities off the switch statement, you can do better. If you do it like this:

#define IF_IN_LIST(expr,list) switch (expr) default: if (0) case list:
#define OR : case

then your uses of the macro can now include an optional else clause!

IF_IN_LIST(get_value(), 1 OR 2 OR 3)
do_stuff();
else
do_other_stuff();

(And naturally both versions work with either bare statements or braced blocks.)

Also at Dreamwidth. (
comments | Leave a comment )
Previous post Next post
Up