Search⌘ K
AI Features

Loop Controls

Explore how to manage loop execution in Solidity using break and continue statements to control flow within smart contracts. Understand the require statement to enforce conditions and handle errors, ensuring robust contract functionality. By the end of this lesson, you will be able to apply these control structures to optimize contract behavior and maintain secure, predictable code.

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:

Solidity
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:

Solidity
// 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: ...