Friday, April 13, 2007

The Clayton's #if*

Users of C++ will be familiar with the use of the pragma directive '#if' to optionally compile a section of code or, indeed, switch between two sections of code when debugging.

I've found an interesting little trick that allows you to achieve a similar effect using comments, so long as the language you're using supports both the line ('//') and block ('/*..*/') styles. The trick comes from how these two styles interact with each other.

Let's start by considering a simple 2 line statement block that has been commented out:
/*
printf ("Now you see it");
printf ("Now you don't!");
*/
What happens if the start of the comment block is, itself commented out?
//*
printf ("Now you see it");
printf ("Now you don't!");
*/ syntax error!
Not very promising, but let's comment out the end block as well:
//*
printf ("Now you see it");
printf ("Now you don't!");
//*/
Now, we see the two comment block markers are commented out, and the embedded block is active. It can be toggled on or off simply adding or removing an extra leading slash. So, to deactivate the block with one change:
/*
printf ("Now you see it");
printf ("Now you don't!");
//*/
The benefits of this are that you don't need to hunt through the code looking for the matching end of the comment block.

Now, we can extend this idea further. Let us split up the block so that one section or the other is not active. The trick here is to identify a character sequence that ends a comment and starts one:
//*
printf ("Now you see it");
/*/
printf ("Now you don't!");
//*/
In this case, the first block is active. The new line therefore acts as the start of a comment. However, simply by removing the first slash:
/*
printf ("Now you see it");
/*/
printf ("Now you don't!");
//*/

The first block is now commented out, and the second block is activated.

Have fun!
*For non-Australians, 'Claytons' is a brand of non-alcoholic beverage popular in the eighties. It was billed as 'the drink you have when you're not having a drink.'. The term 'a clayton's xxx' has passed into common use, with just about anything being substituted (literally!) for 'xxx'.