89DEVs

bool - Boolean Data Type in Solidity

Like other programming languages, Solidity has a boolean data type. It is used for values that are binary, a boolean is either true or false. This makes booleans very efficient to store.

To declare a boolean in Solidity, the bool keyword is used:

bool my_boolean;

default value of boolean

The default value of a boolean in Solidity is false. We have to declare a boolean as true, otherwise, it will be false. // boolean data type has a default value of false bool test1; // defaults to false bool test2 = true; // true

size of boolean

The boolean data type is a very efficient way of storing information. The outcome is always binary: true or false. Therefore a boolean takes only 1 bytes of storage in Solidity.

bool to uint

We can use the ternary operator to convert booleans to integers: 0 for false and 1 for true. // convert bool to uint bool myBool = true; uint myFlag = myBool ? uint(1) : uint(0); Booleans can also be used as return values of functions. // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; contract booleanReturnExample { bool public isChecked; function set_checked() public returns (bool) { isChecked = true; return isChecked; // return boolean value true } } In this contract the boolean isChecked is first declared as false. After the function is called the boolean variable is changed to true.

boolean operators

  • logical negation !
  • logical conjunction &&
  • logical disjunction ||
  • equality ==
  • inequality !=
The following code shows the use of boolean operators and related output: // SPDX-License-Identifier: MIT pragma solidity ^0.8.1; contract BooleanOperators { bool public bool1 = true; bool public bool2 = false; bool public conjunction = bool1 && bool2; // output false bool public disjunction = bool1 || bool2; // output true bool public equality = bool1 == bool2; // output false bool public inequality = bool1 != bool2; // output true bool public negation = !bool1 == bool2; // output true }

        

Summary

Click to jump to section