Consider the two equivalent functions
void foo( )
{
if( unlikely_case )
return;
// foo code
}
void foo( )
{
if( !unlikely_case )
{
// foo code
}
}
Obviously, the compiler can't decide which case is more likely -- but I know ahead of time.
I feel that I should structure my code in the latter form since it is supports what I know of branch prediction.
The issue is this can get ugly
void foo( )
{
if( !sanity_check[ 0 ] )
return;
if( !sanity_check[ 1 ] )
return;
if( !sanity_check[ 2 ] )
return;
// foo code
}
vs
void foo( )
{
if( sanity_check[ 0 ] )
if( sanity_check[ 1 ] )
if( sanity_check[ 2 ] )
{
// foo code
}
}
Is there a keyword I can use to let the compiler know which cases are more likely (probably compiler dependant)? If not, are these sanity-check situations something the compiler takes into consideration when optimizing code for branch prediction? Should I just get used to the pyramidal, latter code?
For the sake of the question, consider only the most popular compilers like MSVC, GCC, clang, etc.