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

余生颓废 提交于 2019-12-04 17:40:27

问题


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?


回答1:


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




回答2:


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".



来源:https://stackoverflow.com/questions/51797959/how-to-use-c20s-likely-unlikely-attribute-in-if-else-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!