2 min read

If Else Statements

Introduction

If-else statements are an essential control structure in programming languages, and Solidity is no exception. They allow developers to specify different code paths depending on the outcome of a condition. In this blog post, we will explain how if-else statements work in Solidity 0.8.16.

Syntax

The syntax of the if-else statement in Solidity is as follows:

if (condition) {
   // execute this code if the condition is true
} else {
   // execute this code if the condition is false
}

The condition can be any expression that evaluates to a boolean value. The code inside the if statement is executed if the condition is true. Otherwise, the code inside the else statement is executed.

In Solidity, the if statement can also be used without the else statement. In this case, if the condition is true, the code inside the if statement is executed, and if the condition is false, the program continues executing the next statement after the if block.

Example

Let's take a look at a simple example to understand how if-else statements work in Solidity.

pragma solidity 0.8.16;

contract Example {
    string public message;

    function checkAge(uint _age) public {
        if (_age > 18) {
            message = "You are an adult";
        } else if (_age == 18){
            message = "you are 18!";
        } else {
	        message = "You are too young"
        }
    }
}

In this example, we have a contract named Example that contains a public variable age that is set to 20 and a public variable message that is set to "You are too young".

The checkAge function checks the value of age and updates the value of message based on the condition. If age is greater than or equal to 18, then the message is updated to "You are an adult". Otherwise, the message is updated to "You are too young".

Ternary operators

In Solidity 0.8.16, ternary operators are used to simplify the syntax for conditional expressions. They are often used to assign a value to a variable based on whether a condition is true or false.

pragma solidity 0.8.16;

contract Example {
    string public message;

    function checkAge(uint _age) public {
        // only works for if else, 
        // not if, else if, else
		message = _age > 18 ? "You are an adult" : "You are too young";
    }
}

Conclusion

If-else statements are an essential control structure in Solidity, allowing developers to specify different code paths depending on the outcome of a condition. In this blog post, we explained how if-else statements work in Solidity 0.8.16, provided an example of how to use them, and discussed nested if-else statements.

Feedback

Have feedback? Found something that needs to be updated, accurate, or explained?

Join our discord and share what can be improved.

Any and all feedback is welcomed.