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?
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]] {
See Likelihood attributes [dcl.attr.likelihood]:
void g(int); int f(int n) { if (n > 5) [[unlikely]] { // n > 5 is considered to be arbitrarily unlikely g(0); return n * 2 + 1; } switch (n) { case 1: g(1); [[fallthrough]]; [[likely]] case 2: // n == 2 is considered to be arbitrarily more g(2); // likely than any other value of n break; } return 3; }