Order of Operations
Introduction
Solidity is a programming language designed for writing smart contracts on the Ethereum blockchain. It is a statically typed language with a syntax similar to that of C++. One important aspect of Solidity, as with any programming language, is the order of operations, which is the order in which operations are performed when evaluating an expression.
In this blog post, we will explore the order of operations in Solidity and provide examples of how it can impact the outcome of a program.
Order of Operations:
The order of operations in Solidity is similar to that of other programming languages. The following table shows the order of operations, from highest to lowest precedence:
| Precedence | Operator | Description. |
| ----------- | -------------- |---------------------------------------- |
| 1 | () | Parentheses (grouping) |
| 2 | ! ~ ++ -- - + | Unary operators |
| 3 | * / % | Multiplication, division, modulo |
| 4 | + - | Addition and subtraction |
| 5 | << >> | Bitwise shift operators |
| 6 | < <= > >= | Comparison operators |
| 7 | == != | Equality operators |
| 8 | & | Bitwise AND |
| 9 | ^ | Bitwise XOR |
| 10 | | | Bitwise OR |
| 11 | && | Logical AND |
| 12 | || | Logical OR |
| 13 | ? : | Ternary conditional operator |
| 14 | = += -= *= /= | Assignment operators |
| | %= <<= >>= &= | |
| | ^= |= | |
| 15 | , | Comma operator |
Note that operators with higher precedence are evaluated before operators with lower precedence. For example, multiplication is evaluated before addition.
Examples:
Let's explore some examples to see how the order of operations can impact the outcome of a program.
Example 1:
uint256 x = 10;
uint256 y = 2;
uint256 z = x + y * 3;
In this example, the order of operations is followed, and the multiplication is performed before the addition. Therefore, y * 3
is evaluated first, resulting in 6. Then, 6 is added to x, resulting in 16.
Example 2:
```uint256 x = 10;
uint256 y = 2;
uint256 z = (x + y) * 3;
In this example, the parentheses are used to group the addition before the multiplication. Therefore, x + y
is evaluated first, resulting in 12. Then, 12 is multiplied by 3, resulting in 36.
Example 3:
uint256 x = 10;
uint256 y = 2;
uint256 z = x / y + 1;
In this example, the order of operations is not followed, and the addition is performed before the division. Therefore, x / y
is evaluated first, resulting in 5. Then, 1 is added to 5, resulting in 6.
Conclusion:
The order of operations is an important aspect of Solidity, and understanding it can help you write more efficient and bug-free code. By following the order of operations, you can ensure that your expressions are evaluated in the intended order.