Comparing to constant boolean
Learn why there is no need to verify boolean values in Solidity with == true or == false. Instead, simply check for variable or !variable for more efficient code.
Category
gas
Languages
solidity
Analysis Layer
static
Severity
info
There is no need to verify that == true or == false when the variable checked upon is a boolean as well. Instead, simply check for variable or !variable.
Code samples:
contract ConstantBooleanComparison {
bool public myBool;
function setBool(bool _value) public {
myBool = _value;
}
function compareBool() public view returns (bool) {
// Unnecessary comparison
if (myBool == true) {
return true;
} else {
return false;
}
}
function compareBoolSimplified() public view returns (bool) {
// Simplified comparison
return myBool;
}
function compareBoolNegation() public view returns (bool) {
// Check for the opposite value
return !myBool;
}
}
Instead of using myBool == true or myBool == false, it is recommended to directly use myBool or !myBool respectively.
Using myBool simplifies the code and improves readability. Additionally, it eliminates any potential for accidental errors introduced by using == true or == false.
Remember to evaluate variable values directly when working with booleans in Solidity to maintain cleaner and more efficient code.