Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimization, asserts and release mode

Consider a function

void f() {
   assert(condition);

   ...
}

In debug mode, where asserts are enabled, the compiler is free to assume condition holds, since the remaining code will not be executed if it does not.

However, in release mode, I believe the compiler will only see

void f() {
   ...
}

and can no longer assume condition.

Are there any compiler directives or static assert tricks to let compiler know about certain invariants?

like image 270
arhzu Avatar asked May 17 '14 08:05

arhzu


1 Answers

This can't be done in portable C or C++.

Some compilers provide intrinsic functions such as __assume (for MSVC) and __builtin_unreachable (for GCC, ICC, and Clang), that can be used for this purpose.

For example:

void f() {
    __assume(condition); //For MSVC
    /*...*/
}

void f() {
    if (!condition) __builtin_unreachable(); //for GCC and Clang
    /*...*/
}
like image 174
Mankarse Avatar answered Oct 05 '22 22:10

Mankarse