bool type which can have two values: true or false.
The TVM (virtual machine) has only
Booleans are represented as -1 or 0. Not 1! But -1.
INT.Booleans are represented as -1 or 0. Not 1! But -1.
== >= && || ... return bool.
Many standard library functions also return bool values:
Logical operators accept both int and bool
- operator
!xsupports bothboolandint - the condition of
ifand similar statements accepts bothboolandint(!= 0) - logical
&& ||accept bothboolandint; for example,a && bevaluates to true when both operands aretrue, and for integers when both operands are non-zero
Logical vs bitwise operators
Tolk has both bitwise& ^ | and logical && || operators. Both can be used for booleans and integers.
The main difference is that logical are short-circuit: the right operand is evaluated only if required to.
| Expression | Behavior |
|---|---|
condition & f() | f() is called always |
condition && f() | f() is called only if condition |
condition | f() | f() is called always |
condition || f() | f() is called only if condition is false |
!x for int results in asm 0 EQINT, but !x for bool results in asm NOT.
Bitwise operators may sometimes be used instead of logical operators to avoid generating conditional branches at runtime.
For example, (a > 0) && (a < 10), being replaced with bitwise, consumes less gas.
Future versions of the compiler may perform such transformations automatically, although this is non-trivial.
Casting to int via as operator
bool is guaranteed to be -1/0 at the TVM level.
Q: Why are booleans -1, not 1?
In TVM, there are only integers. When all bits in a signed integer are set to 1, it equals -1 in a decimal representation. This makes bitwise operations more intuitive — for example,NOT 0 naturally becomes -1.
true=-1— all bits set to 1false=0— all bits set to 0
NOT 0 naturally becomes -1.
It is consistent across TVM instructions. For example, operator a > b is asm GREATER, which returns -1 or 0.