Saturday 3 May 2014

Save a line - assign and test

In C++ if you Get() a member pointer and then check if it's null before you use it (which is probably quite a common occurrence) and you're using two lines to do it in, you can save a line by testing the result of the assignment inline.
 Player player1 = PlayerManager.GetPlayer(1);  
 if (player1 != NULL)  
 {  
    player1.doStuff();  
 }  

becomes:

 if (Player player1 = PlayerManager.GetPlayer(1))  
 {  
    player1.doStuff();  
 }