Thursday, January 13, 2011

Valid, yet scary, code syntax

I recently encountered a scary piece of code syntax which is actually valid, but nevertheless, very confusing. The gist of it was like this (sorry for code formatting):

 if ( myobject == null )  
 {  
   *misc stuff done here*  
   myobject->PrintInfo();  
 }  

For most programmers taking a first look at snippet, it would be a huge red flag of a potential crash waiting to happen. Why the heck would you check for a pointer being null, then call a method on it? However, it ends up this is perfectly valid because the 'PrintInfo()' method looks something like this:

 void PrintInfo ()  
 {  
   if ( this != null )  
   {  
     *do work*  
   }  
 }  

PrintInfo does a null check on the this pointer before accessing any members, which will prevent a crash if the pointer you call the method on is null. This will compile and run without errors, but is sure to drive other programmers up a tree when they see it :D