Loop Controls
Learn about different loop controls in Solidity.
We'll cover the following...
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:
while (condition) {// Run a code if code evaluates to trueif(expression){//Stop the loop execution if the expression evaluates to truebreak;}}
This code example demonstrates the use of the break statement in Solidity:
// SPDX-License-Identifier: MITpragma solidity ^0.8.17;contract LoopControlDemo{// Declaring a dynamic arrayuint public lastIndex;uint index;// Defining the store() function to check the loop control operationfunction store() public{while(index < 5){// Running the code until the while condition is trueindex++;if(index == 4){lastIndex = index;// Using the break statement to stop the while loop executionbreak;}}}}
Line 3: We establish a contract titled
LoopControlDemo.Line 6: We declare a state variable labeled
lastIndexof theuinttype with the purpose of storing the value of the last index.Line 7: We declare a state variable named
indexof theuinttype which monitors the iteration progress within the loop.Line 10: We define a function named
store()with thepublicvisibility specifier and no specified return type.Line 11: We initialize a
whileloop, conditioned uponindex < 5.Line 13: In the loop, we increment the value of the
indexvariable by one using the++operator.Line 14: We examine whether the
index...