How to use C++20's likely/unlikely attribute in if-else statement

前端 未结 3 633
借酒劲吻你
借酒劲吻你 2020-12-05 17:23

This question is about C++20\'s [[likely]]/[[unlikely]] feature, not compiler-defined macros.

This documents (cppreference) only gave an ex

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 17:55

    As of today, cppreference states that, for example, likely (emphasis mine):

    Applies to a statement to allow the compiler to optimize for the case where paths of execution including that statement are more likely than any alternative path of execution that does not include such a statement.

    That suggests that the place to put the attribute is in the statement that is most likely, i.e.:

    if (condition) { [[likely]] ... } else { ... }
    

    This syntax is accepted, for example, by Visual Studio 2019 16.7.0 when compiling with /std:c++latest.

提交回复
热议问题