Solidity – Operators
In Solidity, operators are used to perform various operations on variables. The most common types of operators include:
- Arithmetic Operators: These operators are used to perform mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
pragma solidity ^0.8.0;
contract Example {
uint a = 5;
uint b = 2;
uint c;
function calculate() public {
c = a + b; // c = 7
c = a - b; // c = 3
c = a * b; // c = 10
c = a / b; // c = 2
c = a % b; // c = 1
}
}
- Comparison Operators: These operators are used to compare two values and return a Boolean result. They include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
pragma solidity ^0.8.0;
contract Example {
uint a = 5;
uint b = 2;
bool c;
function compare() public {
c = a == b; // c = false
c = a != b; // c = true
c = a > b; // c = true
c = a < b; // c = false
c = a >= b; // c = true
c = a <= b; // c = false
}
}
- Logical Operators: These operators are used to perform logical operations such as and (&&), or (||), and not (!).
pragma solidity ^0.8.0;
contract Example {
bool a = true;
bool b = false;
bool c;
function logic() public {
c = a && b; // c = false
c = a || b; // c = true
c = !a; // c = false
}
}
- Bitwise Operators: These operators are used to perform bitwise operations on integers such as and (&), or (|), xor (^), not (~), left shift (<<), and right shift (>>).
pragma solidity ^0.8.0;
contract Example {
uint a = 5;
uint b = 3;
uint c;
function bitwise() public {
c = a & b; // c = 1
c = a | b; // c = 7
c = a ^ b; // c = 6
c = ~a; // c = -6
c = a << 2; // c = 20
c = a >> 1; // c = 2
}
}
5. Assignment Operators: These operators are used to assign a value to a variable. The most common assignment operator is the equal sign (=), but there are also several shorthand assignment operators that can be used to perform an operation and then assign the result to a variable. These include:
+=
(addition assignment)
-=
(subtraction assignment)
*=
(multiplication assignment)
/=
(division assignment)
%=
(modulus assignment)
&=
(bitwise and assignment)
|=
(bitwise or assignment)
^=
(bitwise xor assignment)
<<=
(left shift assignment)
>>=
(right shift assignment)
pragma solidity ^0.8.0;
contract Example {
uint a = 5;
uint b = 3;
uint c;
function assignment() public {
c = a; // c = 5
c += b; // c = 8
c -= a; // c = 3
c *= a; // c = 15
c /= b; // c = 5
c %= a; // c = 0
}
}
6. Conditional (Ternary) Operator: This operator is used to perform a conditional operation based on a Boolean expression. The syntax for the conditional operator is expression ? value1 : value2
. If the expression
is true, the operator returns value1
, otherwise it returns value2
.
pragma solidity ^0.8.0;
contract Example {
uint a = 5;
uint b = 3;
uint c;
function ternary() public {
c = (a > b) ? a : b; // c = 5
}
}