Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the purpose of C++20's [[likely]] or [[unlikely]] attribute

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/

EDIT: The intention with this question, is besides to learn and understand for myself and others out there, to trigger a discussion. A discussion that provides reasonable use cases for where it absolutely makes sense from an optimization and efficient programming to use these instructions.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading