C++20: [[{,un}likely]]: fix the position of attributes in example (#97)

This commit is contained in:
Marco Wang
2021-05-15 11:27:07 +08:00
parent 17f4bc150c
commit 76138c2a49
2 changed files with 40 additions and 6 deletions

View File

@@ -265,15 +265,32 @@ for (auto v = std::vector{1, 2, 3}; auto& e : v) {
```
### likely and unlikely attributes
Provides a hint to the optimizer that the labelled statement is likely/unlikely to have its body executed.
Provides a hint to the optimizer that the labelled statement has a high probability of being executed.
```c++
switch (n) {
case 1:
// ...
break;
[[likely]] case 2: // n == 2 is considered to be arbitrarily more
// ... // likely than any other value of n
break;
}
```
If one of the likely/unlikely attributes appears after the right parenthesis of an if-statement,
it indicates that the branch is likely/unlikely to have its substatement (body) executed.
```c++
int random = get_random_number_between_x_and_y(0, 3);
[[likely]] if (random > 0) {
if (random > 0) [[likely]] {
// body of if statement
// ...
}
```
[[unlikely]] while (unlikely_truthy_condition) {
It can also be applied to the substatement (body) of an iteration statement.
```c++
while (unlikely_truthy_condition) [[unlikely]] {
// body of while statement
// ...
}