Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES.87 (redundant == or !=) Add my_condition == true example #2185

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CppCoreGuidelines.md
Original file line number Diff line number Diff line change
@@ -13281,6 +13281,10 @@ Helps make style consistent and conventional.
By definition, a condition in an `if`-statement, `while`-statement, or a `for`-statement selects between `true` and `false`.
A numeric value is compared to `0` and a pointer value to `nullptr`.

// Assuming that "my_condition" is a `bool` variable
if (my_condition) { ... } // good
if (my_condition == true) { ... } // redundant ==true, not recommended

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would have been better if you had another example:

if (true == my_condition) { ... }  // redundant but preferred if it must be specified

Reason being - some like myself prefer to have the redundancy obvious - being explicit over implicit. However, having the true as the l-value and the variable as the r-value prevents errors with = vs == from happening.

So there should be a middle ground between the implicit my_condition and the explicit.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@BenjamenMeyer Thank you for your suggestion. I know that if (true == my_condition) would prevent an accidental assignment, that would happen when doing if (my_condition = true), accidentally. But honestly, I still prefer to have the "unknown" (the variable) at the left side, and the "known value" (the constant) at the right side, because I find it more intuitive.


// These all mean "if p is not nullptr"
if (p) { ... } // good
if (p != 0) { ... } // redundant !=0, bad: don't use 0 for pointers