Loop Controls

Learn about different loop controls in Solidity.

Solidity gives us complete control over loop statements. There might be times when we need to exit a loop without reaching its bottom. We might also wish to skip a section of our code block and begin the following iteration of the loop. Solidity includes the break and continue statements to handle all of these scenarios. These statements are used to exit any loop instantly or to begin the next iteration of any loop.

The break statement

The break statement is used to leave a loop early by breaking out of the curly braces that surround it. The syntax for this is as follows:

Press + to interact
while (condition) {
// Run a code if code evaluates to true
if(expression){
//Stop the loop execution if the expression evaluates to true
break;
}
}

This code example demonstrates the use of the break statement in Solidity:

Press + to interact
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract LoopControlDemo{
// Declaring a dynamic array
uint public lastIndex;
uint index;
// Defining the store() function to check the loop control operation
function store() public{
while(index < 5){
// Running the code until the while condition is true
index++;
if(index == 4){
lastIndex = index;
// Using the break statement to stop the while loop execution
break;
}
}
}
}
  • Line 3: We establish a contract titled LoopControlDemo.

  • Line 6: We declare a state variable labeled lastIndex of the uint type with the purpose of storing the value of the last index.

  • Line 7: We declare a state variable named index of the uint type which monitors the iteration progress within the loop.

  • Line 10: We define a function named store() with the public visibility specifier and no specified return type.

  • Line 11: We initialize a while loop, conditioned upon index < 5.

  • Line 13: In the loop, we increment the value of the index variable by one using the ++ operator.

  • Line 14: We examine whether the index ...