Control Structures

Learn about conditional statements in Solidity and how we can use them to implement smart contracts.

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.

Press + to interact
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.

Press + to interact
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;
}
}

Solidity also allows chaining ...