6

I have been reading more on C++ 20, and recently noticed the [[likely]] or [[unlikely]] attributes. Which seems like an interesting concept, not found in previous versions of C++. According to the official CPP Reference:

Allow the compiler to optimize for the case where paths of execution including that statement are more or less likely than any alternative path of execution that does not include such a statement.

What does this really imply?

This blog post, argues against using them because it seems more like pre-mature form of optimization and a few other details. https://blog.aaronballman.com/2020/08/dont-use-the-likely-or-unlikely-attributes/

Alix Blaine
  • 585
  • 2
  • 16
  • 3
    One example is that if you call a function inside of an `[[unlikely]]` branch, even if the function is small it might not be inlined, since inlining it would increase the function's size with code that is unlikely to be reached – Filipe Rodrigues Apr 07 '23 at 13:08
  • 2
    Looks like another question has answers to this one: [How do the likely/unlikely macros in the Linux kernel work and what is their benefit?](https://stackoverflow.com/q/109710) – mouviciel Apr 07 '23 at 13:12
  • @FilipeRodrigues, seems very odd. Kind of a waste, but, also by the same token, it seems to give the programmer the freedom of control in terms of instructing the compiler for certain level of optimization. This is my understanding based on your explanation here. – Abigail Johnsson Apr 07 '23 at 13:13
  • @mouviciel, not the same question mate. Please, this is not a duplicate. I googled for hours and days, I even seen that link before. Thanks. – Abigail Johnsson Apr 07 '23 at 13:13
  • 1
    @AbigailJohnsson - I didn't say that the questions are the same. I just thought that the accepted answer there may be valuable in the context of this one. – mouviciel Apr 07 '23 at 14:32
  • 4
    ‘triggering discussion’ is not really what this site is for. In fact, there’s a whole process for closing questions that only ask for people’s opinions. – user3840170 Apr 07 '23 at 16:27

1 Answers1

17

It's meant to let the compiler know which path is the "fast path", as in "more likely to happen".

For example, imagine implementing vector::at. This function throws if the index is out of bounds. But you expect this situation to happen very rarely, most of the time you expect the users to access a valid element. You can mark the throwing path [[unlikely]] and the compiler will understand your intention and might optimize the program accordingly.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93