May 1999 Obfuscated C++

.
Last Month's Obfuscated C++

Last month we asked you to suggest the smallest replacement for the first line that would enable this program to compile without error:
// What goes here?
void f() {
	struct i i(i[i[i]=i]=i);
}
Here's the smallest example I could come up with:
struct i{i&operator[](i&);}i;
void f() {
	struct i i(i[i[i]=i]=i);
}
The first line declares a class named i and defines an object of that class, also named i. According to the ISO/ANSI Standard section 3.3, such apparently duplicate declarations in the same scope are legal as long as one of them declares a class or enumeration and the other declares an object. In this case the class/enumeration name is hidden, but it may still be invoked explicitly by using an elaborated type specifier. So in our code, i refers to the object, while struct i refers to the class.

Our class includes a declaration of operator[] such that applying it to a pair of struct i objects returns a reference to a struct i.

The statement inside of f defines another object of struct i, also named i. It is initialized with an expression that is the result of applying a series of operator[] and assignment operators to i. Because we have not defined a copy assignment operator for struct i, we get the default version, which returns a (non-const) reference to struct i.

Note that the point of declaration of the inner i occurs after the declarator, but before the initializer of that declaration. Because the initializer of the inner i is the expression in parentheses, we are actually initializing i with a reference itself, much as if we had said:

struct i i(i);

This will have undefined behavior, but our requirement was that the above code only compile, not execute!



This Month's Obfuscated C++

This month's puzzle is adapted from an example originally written by Don Libes.1 Explain the semantics of the function f in the following code:
bool n(void* s) {
	return ((*(long*)s-0x01010101)&~(*(long*)s)&0x80808080);
}

int f(char* p) {
	int r = 0;
	while(!n(p))r+=4,p+=4;
	while(*p++)++r;
	return r;
}
(Note: While this code is not guaranteed to be portable, it should run correctly on most current C++ implementations.)

Reference
1. Libes, D. Obfuscated C and Other Mysteries, John Wiley & Sons, New York, NY, p. 209, 1992.

 



Rob Murray is Manager, 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 the C++ Report and can be contacted at [email protected].