Suppose I have two C++ functions for debug output:
void Trace( const wchar_t* format, ... )
{
va_list args;
va_start( args, format );
VarArgTrace( format, args );
va_end( args );
}
void VarArgTrace( const wchar_t* format, va_list args )
{
WCHAR buffer[1024];
//use ::_vsnwprintf_s to format the string
::OutputDebugStringW( buffer );
}
the above uses Win32 OutputDebugStringW(), but it doesn’t really matter. Now I want to optimize the formatting so that when there’s no debugger attached formatting is not done (I measured – speedup is significant):
void Trace( const wchar_t* format, ... )
{
if( !IsDebuggerPresent() ) {
return;
}
//proceed as previously
va_list args;
.....
}
will the fact that I return early once IsDebuggerPresent() returns null affect anything except that formatting will be skipped?
I mean I no longer call va_start and va_end – will this matter? Will skipping va_start and va_end cause any unexpected behavior changes?
The only requirement on an early return is that if you have used (executed)
va_start(), you must useva_end()before you return.If you flout this rule, you’ll get away with it on most systems, but some system somewhere needs the
va_end(), so don’t risk omitting it. It is undefined behaviour to omit it.Other than that rule, it is up to you how you handle your return. Your proposed early return is not a problem.