Open In App

If-Else Statement in Solidity

If-else statement is a type of conditional statement that allows the program to execute one block of code if a certain condition is true and an else block of code is executed if the condition is false. It contains two blocks of code and depending on the condition any one of the blocks is getting executed.

Syntax:



if (condition) {
   //  this block of code is executed if  condition is true
} else {
   // this block of code is executed if condition is false
}

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. 
else: keyword used to execute the block of statement if condition fails.
{ }: enclose the block of code to be executed if the condition is false. 

Below is the Solidity program to implement the if-else statement:




// Solidity program to implement
// if-else statement
pragma solidity ^0.8.15;
 
// Declaring contract
contract Example {
     
  // Declaring one variable
  uint public value;
     
  // Declaring function with argument
  function setValue(uint newValue) public {
     
    // if value is greater than 10
    // value will be assigned as newValue
    if (newValue > 10)
    {
      value = newValue;
         
      // else value will be zero.
    } else
    {
      value = 0;
    }
  }
}

Explanation: In this example, a contract called “Example” is declared that has one variable called “value”. 

Output:

Case 1: If block is executed

value = 12 (greater than 10) so the newValue = 12.

 

Case 2: Else block is executed

value = 8 (less than 10) so the newValue = 0.

 

Article Tags :