Search code examples
c++c++20branch-prediction

C++20: difference between [[likely]], [[unlikely]] and __builtin_expect?


Preliminary information: according to the recent ISO C++ Committee Trip Report, the [[ likely ]] and [[ unlikely ]] attributes for conditional branching will be added in C++20 and is available in the newest version of GNU GCC (you can play with it on the online compiler wandbox.org).


Question: Is the following construction

if (cond) [[ likely ]] { ... }

equivalent to the following one?

if (__builtin_expect(bool(cond), 1)) { ... }

Are there any performance difference or implementation nuances between different compilers that one should be aware of in order to use it effectively?


Solution

  • Is the following construction equivalent to the following one?

    In intention, yes.


    Are there any performance difference or implementation nuances accross compilers that one should be aware of in order to use it effectively?

    As you can see from P0479, there is no mandatory wording requirement on the behavior of these attributes. Their behavior is mentioned as part of a non-normative note, which implementations are encouraged but not forced to follow.

    The only way to answer this question is to check the manual of your compiler.