How to annotate a ternary expression with `[[likely]]`?

Viewed 373

In C++20, is there a way to annotate a ternary expression with [[likely]]/[[unlikely]] to hint the compiler which of the two outcomes is more likely?

The following syntax doesn't seem to work

condition ? [[likely]] function1() : function2()

Is there a different syntax to annotate ternary expressions? Or will I have to use an if instead?

1 Answers

Is there a different syntax to annotate ternary expressions?

No, there is no way to annotate a ternary conditional expression with the [[likely]] attribute.

Or will I have to use an if instead?

Yes. Or alternatively, you can omit the attribute.


For what it's worth, it is possible using the GNU extension:

__builtin_expect(!!condition, 1) ? function1() : function2()
Related