This question is about C++20's [[likely]]
/[[unlikely]]
feature, not compiler-defined macros.
This documents (cppreference) only gave an example on applying them to a switch-case statement. This switch-case example compiles perfectly with my compiler (g++-7.2) so I assume the compiler has implemented this feature, though it's not yet officially introduced in current C++ standards.
But when I use them like this: if (condition) [[likely]] { ... } else { ... }
, I got a warning:
"warning: attributes at the beginning of statement are ignored [-Wattributes]".
So how should I use these attributes in an if-else statement?
The __attribute__ directive is used to decorate a code declaration in C, C++ and Objective-C programming languages. This gives the declared code additional attributes that would help the compiler incorporate optimizations or elicit useful warnings to the consumer of that code.
C++ attribute: likely, unlikely (since C++20) 1) 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.
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With