Control Flow
Solidity has the control structures you know from C-like languages: if/else, for, while, do … while, break, continue and return. There is no switch statement. The new idea is that every loop iteration costs gas, so loops need more care than in an ordinary program.
if / else
Conditions must be bool; braces are optional for single statements, but always using them is clearer.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
function shippingFee(uint256 orderCents) public pure returns (uint256) {
if (orderCents >= 5000) {
return 0; // free shipping from 50.00
} else if (orderCents >= 2000) {
return 299;
} else {
return 599;
}
}
function main() external pure {
console.log("order 1500 ->", shippingFee(1500));
console.log("order 2500 ->", shippingFee(2500));
console.log("order 7000 ->", shippingFee(7000));
}
}order 1500 -> 599
order 2500 -> 299
order 7000 -> 0
for loops
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
function main() external pure {
uint256 sum = 0;
for (uint256 i = 1; i <= 10; i++) {
sum += i;
}
console.log("1 + 2 + ... + 10 =", sum);
// break and continue
for (uint256 n = 1; n < 100; n++) {
if (n % 2 == 0) continue; // skip even numbers
if (n > 9) break; // stop after 9
console.log("odd:", n);
}
}
}1 + 2 + ... + 10 = 55
odd: 1
odd: 3
odd: 5
odd: 7
odd: 9
while and do … while
while checks the condition before each iteration; do … while runs the body at least once.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
function digitCount(uint256 value) public pure returns (uint256 digits) {
do {
digits++;
value /= 10;
} while (value > 0);
}
function gcd(uint256 a, uint256 b) public pure returns (uint256) {
while (b != 0) {
(a, b) = (b, a % b); // tuple assignment swaps in one step
}
return a;
}
function main() external pure {
console.log("digits in 0 :", digitCount(0));
console.log("digits in 90210 :", digitCount(90210));
console.log("gcd(84, 36) :", gcd(84, 36));
}
}digits in 0 : 1
digits in 90210 : 5
gcd(84, 36) : 12
digitCount uses a named return variable (returns (uint256 digits)): it starts at 0 and is returned automatically when the function ends.
Loops and the gas limit
Every block has a gas limit, so a transaction can only do a bounded amount of work. A loop over a list that keeps growing, for example all users who ever registered, will eventually cost more gas than a block allows, and the function becomes impossible to call. This is a real denial-of-service risk.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
function work(uint256 iterations) internal view returns (uint256 used) {
uint256 before = gasleft();
uint256 acc;
for (uint256 i = 0; i < iterations; i++) {
acc += i;
}
used = before - gasleft();
}
function main() external view {
console.log("10 iterations :", work(10), "gas");
console.log("100 iterations :", work(100), "gas");
console.log("1000 iterations:", work(1000), "gas");
}
}10 iterations : 2537 gas
100 iterations : 24947 gas
1000 iterations: 249047 gas
The cost grows linearly with the number of iterations. (The playground compiles without the optimizer, so the numbers are higher than in an optimized production build.)
Good habits:
- Loop only over collections whose size you bound (e.g. "at most 50 candidates").
- Prefer mappings and running totals to "loop over everything".
- Let users process their own entries (a pull design) instead of one function processing everyone.
There is no switch
Use if/else if chains, or a mapping lookup when you're translating keys to values:
mapping(uint8 => uint256) public feeForTier; // tier => fee, filled in the constructorTest yourself
Why can a loop over an ever-growing array be dangerous in a contract?
- Loops are not allowed in Solidity
- It can eventually need more gas than a block allows, making the function uncallable
- Arrays cannot be iterated
- It makes the contract public
What does a function with returns (uint256 total) return if it never executes a return statement?
- It does not compile
- The current value of
total - Always 0
- It reverts
Which statement is NOT available in Solidity?
do ... whilecontinueswitchbreak