On a Friday in 2022, Tim Wiederhake wrote:
The code style showed `bool hasFoos; if (hasFoos == true)` as a
good example in one place, only to warn against comparisons with
`true` a couple of paragraphs further down.
Merge this advice on comparing with `true` into the "Conditional
expressions" section and split the example up for readability.
Signed-off-by: Tim Wiederhake <twiederh(a)redhat.com>
---
docs/coding-style.rst | 60 +++++++++++++++++++++++++++----------------
1 file changed, 38 insertions(+), 22 deletions(-)
diff --git a/docs/coding-style.rst b/docs/coding-style.rst
index dca9de1915..3dedb032f4 100644
--- a/docs/coding-style.rst
+++ b/docs/coding-style.rst
@@ -427,25 +427,47 @@ Conditional expressions
-----------------------
For readability reasons new code should avoid shortening
-comparisons to 0 for numeric types. Boolean and pointer
-comparisons may be shortened. All long forms are okay:
+comparisons to 0 for numeric types:
::
- virFoo *foos = NULL;
size nfoos = 0;
- bool hasFoos = false;
GOOD:
- if (!foos)
- if (!hasFoos)
+ if (nfoos != 0)
if (nfoos == 0)
- if (foos == NULL)
- if (hasFoos == true)
BAD:
- if (!nfoos)
if (nfoos)
+ if (!nfoos)
+
+Prefer the shortened version for boolean values. Boolean values
+should never be compared against the literal ``true``, as a
+logical non-false value need not be ``1``.
+
+::
+
+ bool hasFoos = false;
+
+ GOOD:
+ if (hasFoos)
+ if (!hasFoos)
+
+ BAD:
+ if (hasFoos == true)
+ if (hasFoos != false)
+ if (hasFoos == false)
+ if (hasFoos != true)
I think people would get it even if all four options weren't listed :)
+
+Pointer comparisons may be shortened. All long forms are okay.
+
Either way:
Reviewed-by: Ján Tomko <jtomko(a)redhat.com>
Jano