Lesson 6: Control Structures in Solidity

In the previous lessons, we started to dip our toes deeper and deeper into Solidity, looking at topics such as visibility and functions. In this lesson, we will continue quickly covering control structures.
With regards to control structures, Solidity is very similar to other languages, such as Javascript. We have if, else, for, while, do, break, continue and return just like in other languages.
We have to use parentheses around conditionals, but we can drop the curly bases if our conditional only contains a single statement. Let’s see an example of this:

External calls
To call an external function in your contract, either declared in your own contract (use this.f()) or in another contract (use instance.f() ). Let’s see an example of this:

It is also important to note that the try / catch statements can only be used with external functions. The catch block will be invoked when the external function calls revert. Here is a simple hypothetical example, where we have a PriceFeed contract, and a PriceChecker contract. The latter calls an external function on the former, and it catches the error if the external function reverts.

Unlike internal function calls, which on the EVM level are executed using the the JUMP opcode, external functions use the CALL opcode.
Internal calls
Internal functions of the current contract can be called directly and recursively. Let’s see an example:

These function calls are translated into JUMP opcodes on the EVM level. Passing memory references between internal functions is relatively efficient because the current memory is not cleared between calls, however, we should still be wary of too many recursive calls, because they can get pretty expensive pretty fast.
Here is a final example that uses the control structures that have not been mentioned in this post yet, so you see the syntax for their usage. We use different control structures to increment the value of _a.

Conclusion
In this lesson, we went over the different control structures present in Solidity and also examined the most basic peculiarities that come from running on the blockchain.
Thank you for staying with us till the end. If you enjoyed reading this piece please keep in touch and follow Solidify to keep up with our lessons on Solidity. In the upcoming articles, we will deep dive into the intricacies of the language, progressing from beginner to advanced level.
If you are new to Solidity, the previous lessons might be of value to you.
