Share via


__assumeĀ 

Microsoft Specific

Passes a hint to the optimizer.

__assume(
      expression
)

Parameters

  • expression
    Any expression that is assumed to evaluate to true.

Remarks

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.

__assume is not a true intrinsic. It does not need to be declared as a function and cannot be used in a #pragma intrinsic directive. No code is generated, although it affects the code generated by the optimizer.

Use __assume in an ASSERT only when the assert is not recoverable. __assume should not be used in an assert for which you have subsequent error recovery code; the compiler might optimize away the error handling code.

The most common use of __assume is with the default case of a switch statement, as shown in the following example.

Requirements

Intrinsic Architecture

__assume

x86, IPF, x64

Example

// compiler_intrinsics__assume.cpp
#ifdef DEBUG
# define ASSERT(e)    ( ((e) || assert(__FILE__, __LINE__) )
#else
# define ASSERT(e)    ( __assume(e) )
#endif

void func1(int i)
{
}

int main(int p)
{
   switch(p){
      case 1:
         func1(1);
         break;
      case 2:
         func1(-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.
   }
}

Example Remarks

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 __assume, that code might not run correctly if the expression inside the __assume statement is false at run time. If you are not sure that the expression will always be true at run time, you can use the assert function to protect the code:

# define ASSERT(e)    ( ((e) || assert(__FILE__, __LINE__)), __assume(e) )

Unfortunately, this use of assert prevents the compiler from performing the default-case optimization previously shown. Therefore, you might want to use a separate macro instead:

#ifdef DEBUG
# define NODEFAULT   ASSERT(0)
#else
# define NODEFAULT   __assume(0)
#endif

   default:
      NODEFAULT;

END Microsoft Specific

See Also

Reference

Compiler Intrinsics
C++ Keywords