DEV Community

Cover image for While Loop in Solidity
Shlok Kumar
Shlok Kumar

Posted on

While Loop in Solidity

While loops in Solidity are useful for executing code repeatedly based on a condition

The while loop is the most fundamental loop in Solidity.  In programming, a while loop aims to continue the execution of a statement or code block as long as a certain expression is true. The loop comes to an end when the expression is found to be false.

The do-while loop is similar to the while loop but with one key difference. The code block wrapped inside a {} will be executed at least once before the condition is evaluated. This means that even if the condition evaluates to false, the code block will still be executed once.

Like with while loops, it is important to ensure that do-while loops are bounded so they don't hit the gas limit. When using either type of loop in Solidity, it is important to remember that a conditional expression must be evaluated as true or false. If true, the code block wrapped inside a {} will be executed until the expression becomes false.

While loop

The syntax of while loop in Solidity is as follows −

while (expression) {
   Statement(s) to be executed if expression is true
} 
Enter fullscreen mode Exit fullscreen mode

Solidity While loop example

pragma solidity ^0.8.0; 
  
// Creating a contract 
contract Types { 
      
    // Declaring a dynamic array
    uint[] data; 
    
    // Declaring state variable
    uint8 j = 0;
     
    // Defining a function to 
    // demonstrate While loop'
    function loop(
    ) public returns(uint[] memory){
    while(j < 5) {
        j++;
        data.push(j);
     }
      return data;
    }
} 
Enter fullscreen mode Exit fullscreen mode

Optimization of While loop

When using while loops in Solidity, it is important to consider best practices to ensure that the transaction does not fail due to hitting the gas limit. It is recommended to have bounded loops in which contract state variables are updated for each iteration. Additionally, it is important to avoid unbounded loops as this can also cause a transaction failure.

Optimizing while loops in Solidity can be done by avoiding on-chain writing and reading within loops. This is one of the most significant gas optimizations in Solidity. Other techniques include loop unrolling, loop fusion, loop invariant code motion, and loop peeling.

For example, when using while loops, the condition should be checked at the end of the loop instead of at the beginning. Additionally, movable SSA variable declarations can be moved outside the loop to reduce gas costs. Finally, it is important to consider whether a for or while loop is more appropriate for a given task as they have different gas costs associated with them.

For more content, follow me on - https://linktr.ee/shlokkumar2303

Top comments (0)