From 76138c2a495a39ea779d58018e3bf29773d6eae0 Mon Sep 17 00:00:00 2001 From: Marco Wang Date: Sat, 15 May 2021 11:27:07 +0800 Subject: [PATCH] C++20: [[{,un}likely]]: fix the position of attributes in example (#97) --- CPP20.md | 23 ++++++++++++++++++++--- README.md | 23 ++++++++++++++++++++--- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/CPP20.md b/CPP20.md index 9db0f64..a37052d 100644 --- a/CPP20.md +++ b/CPP20.md @@ -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 // ... } diff --git a/README.md b/README.md index d602f1a..4b556c5 100644 --- a/README.md +++ b/README.md @@ -360,15 +360,32 @@ for (std::vector v{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 // ... }