Conditional Statements
Learn about conditional statements in Solidity.
We'll cover the following...
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:
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:
// SPDX-License-Identifier: MITpragma solidity ^0.8.17;contract ControlDemo{// Declaring variablesuint16 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 resultbool 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
andsecond
, both classified asuint16
. They’re initialized with the values20
and30
, respectively.Line 10: We define a function named
isFirstGreater()
with thepublic
visibility specifier. It has the return ...