Monday, November 20, 2006

Puzzle 2

A really difficult one this time!
The code defines a Logger class and a macro that gets the static instance of the logger and passes the text to its Log method with the log level TRACE_LEVEL.

Unfortunately the code does not compile due to a syntax error.
You can copy the code and try it with your favorite C or C++ compiler.
I get an error that l is not defined, and interestingly there is an 'else
without an if' !




#include <stdio.h>


// define a class for logging
// provides static instance via Instance method
class Logger
{
private:
static Logger* sInstance;


public:
Logger() {};
~Logger() {};


static Logger* Instance()
{
if (!sInstance)
sInstance = new Logger();
return sInstance;
}




void Log(int level, const char* text)
{
printf(text);
}
};


#define TRACE_LEVEL 5


#define TRACE(text) Logger* l = Logger::Instance(); l->Log(TRACE_LEVEL, text);




Logger* Logger::sInstance = 0; //static initialisation




int main(int argc, char* argv[])
{
if (argc == 1)
TRACE("to few parameters");


else
TRACE("at least one parameter");




//do something sensible
return 0;
}






A little hint: there's nothing wrong with the Logger class or the macros, the bug is within the main function!


Happy puzzling!

0 Comments:

Post a Comment

<< Home