Jul
07
2008

Empty Statements

I’ve been seeing a lot of code recently with empty statements. An empty statement is something in code that does something useless whilst doing now. You’re probably wondering how can you do something useful whilst doing nothing, well take this example code into consideration.

#define FREE_MEMORY( x ) free( (x) ); x = 0

It is a macro to free memory and nullify the pointer associated with it. Now when trying to implement it in code.

void main()
{
void * p = 0;

// Okay
FREE_MEMORY( p );

// Okay
if( p )
FREE_MEMORY( p );

// Okay
if( p )
p = 0;
else
FREE_MEMORY( p );

// Bad Syntax
if( p )
FREE_MEMORY( p );
else
p = 0;
}

As you can see, it is all okay until the if-else statement where the FREE_MEMORY() macro comes after. The reason why this fails is that if-else statement only allows one statement after the if and else, scope brackets ({}) are required for more.

So we add scope brackets to the macro.

#define FREE_MEMORY( x ) { free( (x) ); x = 0; }

Now if this macro is treated like another other function and an end statement (;) is used with it, then the if-else will fail again. The reason why this time is because when it is expanded, we have an end statement where there shouldn’t be one.

void main()
{
if( p )
{
free( (p) );
(p) = 0;
}; // End Statement causes syntax error
else
p = 0;
}

So the one way around this is to implement something with scope that is postfixed with an end statement, and does nothing.. a do-while.

#define FREE_MEMORY( x ) do { free( (x) ); x = 0; } while( 0 )

Now when we use it, everything works as it should do when expanded.

void main()
{
if( p )
do
{
free( (p) );
(p) = 0;
} while( 0 );
else
p = 0;
}

The do-while is a scoped statement, and since it’s continuation argument is set to 0 (false), it will exit when finished.

Written by Kaluriel in: Code | Tags:

No Comments »

RSS feed for comments on this post. TrackBack URL

Leave a comment

You must be logged in to post a comment.

Theme: TheBuckmaker.com Blog Themes | The best Webhosting Plans, Eigenes Internet Radio