Control Flow
More about Solidity
When first learning about how to write smart contract functions, we first focus on making sure that our syntax is correct before everything else. Therefore, if you have looked deeply into your starter code, you will notice that your code is purely sequential. That is, every single line of code inside of your functions are executed in a linear manner. While easy to write and understand, writing purely sequential code means that our contracts will behave the exact same way, regardless of the arguments passed in or the state of the contract. If we want our functions to behave differently based on the arguments passed in and the state of the contract, we will want to embrace control flow in our code
If/Else Statements
The first type of control flow that we will examine is the if/else statement; below is an example of an if/else statement in Solidity:
If we wanted to add multiple branches to our if/else statement, we would do the following:
For Loops
The next type of control flow that we will examine are for-loops; for-loops allow us to iterate over a range of integers. Below is the general syntax for for-loops:
Below is an implementation of the factorial algorithm, which uses for-loops:
Although not necessary, we usual set the type of the loop variable to type uint256 (uint) as this will become useful when indexing into arrays.
While Loops
The last type of control flow that we will examine are while loops. Below is the general syntax of while loops in Solidity: