__assume
Microsoft Specific
__assume(expression)
The __assume keyword passes a hint to the optimizer. The optimizer assumes that the condition represented by expression is true at the point where the keyword appears and remains true until expression is altered (for example, by assignment to a variable). Selective use of hints passed to the optimizer by __assume can improve optimization.
The most common use of __assume is with the default case of a switch statement, as shown below.
Example
#ifdef DEGUG
# define ASSERT(e) ( ((e) || assert(__FILE__, __LINE__) )
#else
# define ASSERT(e) ( __assume(e) )
#endif
void gloo(int p)
{
switch(p){
case 1:
blah(1);
break;
case 2:
blah(-1);
break;
default:
__assume(0);
// This tells the optimizer that the default
// cannot be reached. As so it does not have to generate
// the extra code to check that 'p' has a value
// not represented by a case arm. This makes the switch
// run faster.
}
}
The use of __assume(0) tells the optimizer that the default case cannot be reached. As a result, the compiler does not generate code to test whether p has a value not represented in a case statement. Note that __assume(0) must be the first statement in the body of the default case for this to work.
Because the compiler generates code based on the __assume statement, that code may not correctly if the expression inside the __assume statement is false at runtime. If you are not sure that the expression will always be true at runtime, you can use the assert function to protect the code:
Example
# define ASSERT(e) ( ((e) || assert(__FILE__, __LINE__)), __assume(e) )
Unfortunately, this use of assert prevents the compiler from performing the default-case optimization shown above. Therefore, you may want to use a separate macro instead:
Example
#ifdef DEBUG
# define NODEFAULT ASSERT(0)
#else
# define NODEFAULT __assume(0)
#endif
default:
NODEFAULT;
END Microsoft Specific