September 1999 Obfuscated C++

.
Last Month's Puzzle

Last month we asked you to predict the value returned from this function:
int x=2,y=3,z=4;
	int*a=&x,b=5,c=6,*d=&y,e=7,f=8,*g=&z;
	int h(){
		return
		*a//*//
		*b /*//
		*c /*//
		*d /*/
		*e  */
		*f   *
		*g;
}
The trick is to figure out where the comments start and stop. Remember that comments do not nest. A // comment causes everything on the rest of the line to be ignored; in particular, any succeeding /* on that line does not start a new multiline comment. Similarly, once a /* is seen, everything, including a // sequence, is ignored until the first */ sequence is found.

Here's the code again, with the commented-out sections in bold:
int x=2,y=3,z=4;
	int*a=&x,b=5,c=6,*d=&y,e=7,f=8,*g=&z;
	int h(){
		 return
		*a//*//
		*b /*//
		*c /*//
		*d /*/
		*e  */
		*f  *
		*g;
}
Note how the /* on the line containing b matches the */ on the line containing c. The next two lines work the same way. With the comments removed, the function reads:
int h(){
		return *a * b / *d * f * *g;
	}
Which, if we follow the definitions of the pointers a, d, and g, and the constants b and f, gives us:

	return 2 * 5 / 3 * 8 * 4;
Which is the value 96.



This Month's Puzzle

This month's puzzle is based on one sent to me by Martin Sebor. Explain the semantics of the macro B in the following code:
template 
	struct o
	{
		enum{OO=I%10+i*o::OO};
	};

	template 
	struct o<0,i>
	{
		enum {OO=0};
	};

	#define B(i,I) (o::OO)
Warning: This example uses template-partial specializations. I compiled it successfully using GCC 2.8.1, but many other compilers don't yet implement this feature correctly.



Rob Murray is Director, Engineering at the Irvine office of Net Explorer, an object-oriented software consulting company based in Houston, TX. He has taught C++ at technical conferences since 1987 and is the author of C++ Strategies and Tactics. He was the founding editor of C++ Report and can be contacted at [email protected].