Operators & Control Flow
Notes: shifts never overflow-check (x << 300 is just 0); ** with a negative base is allowed for signed types; % follows the sign of the left operand; division by zero and modulo by zero revert with Panic(0x12).
10.1 Operators
+ - * / % ** (unary - only for signed) ++ -- (prefix and postfix) cond ? a: b
Notes: shifts never overflow-check (x << 300 is just 0); ** with a negative base is allowed for signed types; % follows the sign of the left operand; division by zero and modulo by zero revert with Panic(0x12).
10.2 Control flow
There is no switch statement in Solidity (Yul has one), and no goto. Loops over unbounded data are dangerous: they can exceed the block gas limit (see DoS in Chapter 33).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Flow {
function classify(uint256 x) external pure returns (string memory) {
if (x == 0) {
return "zero";
} else if (x < 10) {
return "small";
} else {
return "large";
}
}
function loops(uint256 n) external pure returns (uint256 evens, uint256 total) {
for (uint256 i = 0; i < n; ++i) {
if (i % 2 == 1) continue;
if (i > 100) break;
evens++;
}
uint256 j;
while (j < n) { total += j; j++; }
do { total += 1; } while (false);
}
function tuple() external pure returns (uint256 a, uint256 b) {
(a, b) = (1, 2);
(a, b) = (b, a); // swap
(, uint256 c) = (5, 6); // skip components
b += c;
}
}10.3 Scoping
Solidity uses C99-style block scoping: variables are visible from their declaration to the end of the enclosing {} block. Shadowing a state variable with a local emits a warning.