OneRaynyDay
OneRaynyDay

Reputation: 3968

Why [[likely]] attribute in C++20 raises a warning here?

#include <iostream>

int foo(int a, int b)
{
    if(a < b) [[likely]] {
        return a;
    }
    return b;
}

int main()
{
    std::cout << foo(3,1) << std::endl;
}

Demo

According to the reference, it seems like this is how we're supposed to decorate if clauses with [[likely]] or [[unlikely]] attributes. It's also supported in C++20 (see here).

However, I'm running into a warning:

main.cpp: In function 'int foo(int, int)':
main.cpp:5:15: warning: attributes at the beginning of statement are ignored [-Wattributes]
    5 |     if(a < b) [[likely]] {
      |               ^~~~~~~~~~

The codebase is strict about warnings, and this will cause builds to fail. So, am I doing something wrong, or is this a bug?

g++ version on my macbook:

g++-9 (Homebrew GCC 9.3.0_1) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Upvotes: 7

Views: 3405

Answers (1)

T.C.
T.C.

Reputation: 137330

There's nothing wrong with your code. This is due to GCC's implementer overlooking the fact that attributes on compound-statements are a thing.

[[likely]] if (whatever) {} means something else entirely - it means that the if statement itself is "likely", not a branch of it.

Upvotes: 9

Related Questions