AuditBase
Sign InGet Started
infoG047

Don't compare boolean expressions to boolean literals

Learn about an important Solidity security issue: comparing boolean expressions to boolean literals. Discover why you should avoid if (<x> == true) and instead use if (<x>), and why if (<x> == false) should be replaced with if (!<x>).

Category

gas

Languages

solidity

Analysis Layer

static

Severity

info

In Solidity, it is unnecessary and potentially error-prone to compare boolean expressions directly to boolean literals. This article highlights two common cases and suggests alternative approaches for better readability and maintainability.

Comparing to true

Consider the following code snippet:

if (&lt;x&gt; == true) {
  // Do something if &lt;x&gt; is true
}

Instead of using the explicit comparison to true, a more concise and idiomatic approach can be taken:

if (&lt;x&gt;) {
  // Do something if &lt;x&gt; is true
}

By directly using the boolean expression &lt;x&gt; as the condition, the intent becomes clearer, and the code becomes more concise and readable.

Comparing to false

Similarly, when checking if &lt;x&gt; is false, it is generally better to use the negation operator (!) instead of comparing &lt;x&gt; to false explicitly:

if (&lt;x&gt; == false) {
  // Do something if &lt;x&gt; is false
}

This can be improved by using the negation operator (!):

if (!&lt;x&gt;) {
  // Do something if &lt;x&gt; is false
}




The negation operator (`!`) effectively negates the boolean expression `&lt;x&gt;`, resulting in the same logical outcome without the unnecessary comparison.


## Conclusion



Comparing boolean expressions to boolean literals explicitly might introduce unnecessary complexity to your Solidity code. By avoiding these comparisons and opting for more concise alternatives, such as directly using the boolean expression as the condition or using the negation operator, you can enhance the readability and maintainability of your code.

Remember, in cases like `if (&lt;x&gt; == true)`, use `if (&lt;x&gt;)` instead, and in cases like `if (&lt;x&gt; == false)`, use `if (!&lt;x&gt;)` instead.

Simplifying your code in this way not only improves its readability and maintainability, but it also demonstrates a better understanding of Solidity language features.