4

I have tried placing C++20's [[likely]] and [[unlikely]] attributes at various locations around the condition of a do-while loop, and it seems placing them at the end of the line after the semicolon is accepted by all three major compilers:

int main(int i, char**)
{
    do {
        ++i;
    } while (i < 42); [[likely]]

    return i;
}

However this looks rather strange. Is this really the correct place for the attribute?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
invexed
  • 645
  • 3
  • 10
  • The annotation is placed after the `;`. So wouldn't the meaning be that the `return i` is likely to be executed? Which .... um .... the compiler could infer without the annotation. – Peter Nov 15 '21 at 11:18

1 Answers1

2

Can a C++20 [[likely]] or [[unlikely]] attribute be used on the condition of a do-while loop?

[[likely]] cannot be applied on "conditions". It can be applied on labels and statements.

However this looks rather strange. Is this really the correct place for the attribute?

You've applied the attribute to the return statement. If we adjust whitespace a bit, then you'll see it better:

} while (i < 42);

[[likely]] return i;

You should apply the attribute to the block statement that is the loop body:

do [[likely]] {
eerorika
  • 232,697
  • 12
  • 197
  • 326