In Solidity, like in other programming languages, control structures such as if statements and for loops are used. These allow execution of specific code based on certain conditions. Solidity supports control structures like if, else, while, do, for, break, continue, and return, similar to C language.
Conditional Branching
Using if statements, else if statements, and else statements, different blocks of code can be executed based on conditions.
In the following example, the isOddNumber function checks whether an input value is odd or even. The expression number % 2 signifies the remainder when ‘number’ is divided by 2. The condition following if checks if the remainder is 0, meaning the code following ‘if’ is executed if the remainder is 0. The code following else is executed if the condition is not met.
function isOddNumber(uint256 number) public view returns (bool) {
bool isOdd = false;
if (number % 2 == 0) {
isOdd = false;
} else {
isOdd = true;
}
return isOdd;
}
Loops
for loops and while loops are used to repeatedly execute code as long as certain conditions are met or for a specific number of times.
The sumUp function in the next example calculates the total sum from 0 to 9. It increments i sequentially, starting from 0 to less than 10, adding it to sum.
uint256 i = 0: Assigns 0 toi, starting from 0i < 10: As long asiis less than 10i++: Incrementiby 1 after executing the code in the for loop (until condition 2 is no longer satisfied)
function sumUp() public pure returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 10; i++) {
sum += i;
}
return sum;
}The following example is a reference from Day 11. In this example, a for loop is used within the withdraw function. As long as i is less than s_funders.length array (the number of elements in ‘s_funders’), the three lines of code within the for loop (from the 5th to the 7th line) are executed sequentially.
...
function withdraw() public onlyOwner {
uint256 total = 0;
for (uint256 i = 0; i < s_funders.length; i++) {
address funder = s_funders[i];
total += s_addressToAmount[funder];
s_addressToAmount[funder] = 0;
}
...Control Flow Transfer
break and continue statements are used to control the interruption of processing within a loop or to jump to the next iteration step.
In the next example, within the for loop, break and continue are called under certain conditions. If i is 3, the loop is exited, and the process is interrupted. If i is 5, the loop skips to the next iteration (i = 6).
for (uint i = 0; i < n; i++) {
if (i == 3) {
break; // Interrupts the loop
}
if (i == 5) {
continue; // Jumps to the next iteration step
}
// Code beyond this line is executed if 'i' is not 5 (in case of 3, the loop is exited altogether)
}
```
Comments