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

Based on example from Jacksonville’18 ISO C++ Report the syntax is correct, but it seems that it is not implemented yet:

if (a>b) [[likely]] {

10.6.6 Likelihood attributes [dcl.attr.likelihood] draft


So how should I use these attributes in an if-else statement?

Exactly as you are doing, your syntax is correct as per the example given in the draft standard (simplified to show relevant bits only):

int f(int n) {
    if (n > 5) [[unlikely]] {
        g(0);
        return n * 2 + 1;
    }

    return 3;
}

But you should understand that this feature is a relatively new one, so may only have placeholders in implementations to allow you to set the attributes. This appears apparent from your warning message.


You should also understand that, unless certain wording changes between the latest draft and the final product, even compliant implementations are able to ignore these attributes. They are very much suggestions to the compiler, like inline in C. From that latest draft n4762 (at the time of this answer, and with my emphasis):

Note: The use of the likely attribute is intended to allow implementations to optimize for the case where paths of execution including it are arbitrarily more likely than any alternative path of execution that does not include such an attribute on a statement or label.

Note the word "allow" rather than "force", "require" or "mandate".


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.