Windows下C中__assume的作用

 

Microsoft Specific

__assume(expression)

The __assume keyword passes a hint to the optimizer. The optimizer assumes that the condition represented byexpression is true at the point where the keyword appears and remains true untilexpression 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 whetherp 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 theassert 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值