Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 600
Leedehai Avatar asked Aug 11 '18 08:08

Leedehai


People also ask

What is __ attribute __ in C?

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.

When to use likely c++?

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.


2 Answers

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

like image 77
user7860670 Avatar answered Oct 19 '22 04:10

user7860670


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.

like image 7
Gabriele Giuseppini Avatar answered Oct 19 '22 05:10

Gabriele Giuseppini