Open In App

If Statement in Solidity

Last Updated : 19 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

If statement is a type of conditional statement. It is used to execute a certain block of code or statements only if a certain condition is true else no statement is executed.

Syntax:

if (condition) {
  // code is executed if condition is true
}

Here,

if: keyword used to initiate the conditional statement.
(condition): to check the condition it can be any expression that evaluates to a boolean value (true or false).
{ }: enclose the block of code to be executed if the condition is true.

Below is the Solidity program to implement the if statement:

Solidity




// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.6 <0.9.0;
 
// @title A contract for demonstrate the Solidity Control-Flow
// @notice For now, this contract just show how to implement the if statement
contract IfExample{
   
  // Declaring state variables
  uint x = 100;
  uint y = 50;
   
  // Declaring function
  function check() public view returns (bool)
  {
    if (x < y)
    {
      return true;
    
  }
}


Explanation: In this example, the solidity contract If Example with a function called check takes two unsigned integer arguments x and y, and returns a bool value based on the condition written in the if block. Inside the function, the, if statement checks if x, is greater than y. If the condition is true, we return true.

Output:

If statement

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads