Search⌘ K
AI Features

Control Structures

Explore Solidity control structures including if blocks, while, do while, and for loops to manage conditional logic and iterations. Understand how to use break and continue to control loop flow, enabling you to write effective and functional smart contracts in Ethereum development.

We won’t be able to develop many useful smart contracts without using control structures like conditional statements or loops. Therefore, in this lesson, we'll get an overview of Solidity’s control structures that'll come in handy in the following lessons and exercises.

Conditional statement

Not surprisingly, like many other programming languages, Solidity supports if blocks. They allow defining a code block that'll be executed only if the specified condition is true.

Solidity
function abs(uint num) {
if (num < 0) {
return -num;
}
return num;
}

In the example above, if the num variable is less than zero, we'll return the opposite value of num. Otherwise, we'll return the value of num as is.

We can also add the else block that'll be executed if the specified condition is false.

Solidity
function incrementNumber(uint num) view returns(uint) {
uint res = 0;
if (num % 2 == 0) {
// "num" is even
res += 2;
} else {
// "num" is odd
res += 1;
}
}
...