Arene Base
Fundamental Utilities For Safety Critical C++
Loading...
Searching...
No Matches
Facilities For Optimizing Expected Branches

Arene Base provides a helper for marking that a boolean expression is expected to be true most of the time. The public header is:

#include "arene/base/compiler_support/expect.hpp

Using ARENE_EXPECT to optimize conditionals

The ARENE_EXPECT macro takes a boolean expression as an argument, which is expected to be true most of the time. This expectation is passed to the compiler, so that it may use that information for code generation and optimization.

For example, in the following code, the optional_configuration parameter to the function foo is not expected to be set very often, so most calls will have an empty optional. ARENE_EXPECT is used to convey that expectation to the compiler.

void foo(arene::base::optional<config_data> optional_configuration = {}) {
if (ARENE_EXPECT(!optional_configuration.has_value())) {
do_default_foo_processing();
} else {
do_custom_foo_processing(*optional_configuration);
}
}
Note
If the expectation is incorrect, the compiler will potentially generate sub-optimal code. Therefore, care must be taken to ensure that the expected branch is indeed taken more often than not.