Home Item 30 - likely and unlikely Attributes(English)
Post
Cancel

Item 30 - likely and unlikely Attributes(English)

C++ Attributes

In code, you might occasionally see [[nodiscard]] and other similar syntax in interesting places. These are called attributes, and they serve a specific purpose.

Attributes in C++ are a way to provide the compiler with additional information that can influence how the program is compiled or executed. These attributes can be applied to various program elements such as classes, structures, functions, variables, etc.

Common Attributes

[[nodiscard]]: Indicates that the return value of a function should not be ignored. [[deprecated]]: Marks an element as deprecated, issuing a warning when it is used. [[maybe_unused]]: Indicates that a variable or parameter might be unused, preventing the compiler from issuing a warning about unused variables.

Here’s a simple example:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

[[nodiscard]]
int calculate() {
    return 81;
}

int main() {
    calculate(); // This will produce a compile-time warning because the return value is ignored
    return 0;
}

result

Desktop View

[[likely]] and [[unlikely]]

C++20 introduced the [[likely]] and [[unlikely]] attributes. These attributes are used to indicate to the compiler that a certain branch is more likely or less likely to be chosen at runtime, helping the compiler optimize the code better.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main() {
    int x = 10;

    if (x > 0) [[likely]] {
        std::cout << "x is positive\n";
    } else [[unlikely]] {
        std::cout << "x is non-positive\n";
    }

    return 0;
}

Explanation:

[[likely]]: Indicates that this branch is more likely to be executed. In the example above, if the condition x > 0 is more common, the compiler will optimize this branch for better performance.

[[unlikely]]: Indicates that this branch is less likely to be executed. In the example above, if the condition x <= 0 is less common, the compiler will optimize accordingly.

When to Use

These attributes are particularly useful in scenarios where branch prediction significantly impacts performance:

  1. High-performance data processing.
  2. Error handling in network or I/O operations.
  3. Algorithms where common and rare cases are clearly distinguishable.

Note:

Using these attributes is merely a hint to the compiler, which may choose to ignore them.

These attributes do not change the semantics of the program; they are only used for optimization purposes.

β˜γƒ„β˜

This post is licensed under CC BY 4.0 by the author.

πŸ‘ˆ ツ πŸ‘