Conditional Statements

Learn about conditional statements in Solidity.

Conditional statements are used to do different actions based on certain conditions and are supported by Solidity. Here, we’ll go through the different conditional statements.

The if statement

The if statement enables Solidity to make judgments and carry out assertions conditionally. Here’s the syntax of the if statement:

Press + to interact
if (condition) {
run a code only if condition evaluates to true
}

Here’s a code example of a Solidity smart contract that demonstrates the use of the if statement:

Press + to interact
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract ControlDemo{
// Declaring variables
uint16 public first = 20;
uint16 public second = 30;
function isFirstGreater() public view returns(bool)
{
// Using the if condition to evaluate if the variable first is greater than the variable second, and returning the result
bool result;
if (first > second)
{
result = true;
}
return result;
}
}
  • Line 4: We establish a contract titled ControlDemo.

  • Lines 7–8: We declare two state variables, first and second, both classified as uint16. They’re initialized with the values 20 and 30, respectively.

  • Line 10: We define a function named isFirstGreater() with the public visibility specifier. It has the return ...