Solidity Loop Control
Loop control lets a loop stop early or skip one turn. The two tools are break and continue.
Break stops the search at the first match
This search checks each value in order. It stops as soon as one value is over the limit.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract NumberSearch {
function firstOver(uint256[] memory values, uint256 limit) public pure returns (uint256) {
uint256 position = values.length;
for (uint256 i = 0; i < values.length; i++) {
if (values[i] > limit) {
position = i;
break;
}
}
return position;
}
}
Continue skips the even numbers
This loop adds only odd numbers. Continue sends each even number straight to the next turn.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract OddSum {
function sumOdd(uint256[] memory values) public pure returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < values.length; i++) {
if (values[i] % 2 == 0) {
continue;
}
total += values[i];
}
return total;
}
}
Break can stop a while loop
This loop could run forever without a stop. Break ends it when the total passes the limit.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract StepCounter {
function stepsToPass(uint256 limit) public pure returns (uint256) {
uint256 total = 0;
uint256 steps = 0;
while (true) {
steps += 1;
total += steps;
if (total > limit) {
break;
}
}
return steps;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract ArrayTools {
function firstOver(uint256[] memory values, uint256 limit) public pure returns (uint256) {
uint256 position = values.length;
for (uint256 i = 0; i < values.length; i++) {
if (values[i] > limit) {
position = i;
break;
}
}
return position;
}
function sumOdd(uint256[] memory values) public pure returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < values.length; i++) {
if (values[i] % 2 == 0) {
continue;
}
total += values[i];
}
return total;
}
}
Key points
- Break: an instruction that stops a loop at once.
- Continue: an instruction that skips the rest of one turn.
- Use break to leave a loop as soon as the answer is found.
- Use continue to skip a value that should not be counted.
- Code after break inside a turn does not run in that turn.
In this example, firstOver walks the array and uses break to stop at the first value over the limit. It returns the position of that value. The sumOdd function then walks the same kind of array and uses continue to skip every even number. It adds only the odd numbers and returns the total.
Note
break and continue work in for loops and while loops.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
What does continue do inside a loop?