Solidity – if…else statement

Solidity - if...else statement

This topic is about Solidity – if…else statement.

The ‘if…else’ statement is the next form of control statement that allows Solidity to execute statements in a more controlled way.

Syntax

if (expression) {
   Statement(s) to be executed if expression is true
} else {
   Statement(s) to be executed if expression is false
}

Here Solidity expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are executed.

Example

pragma solidity ^0.5.0;

contract SolidityTest {
   uint storedData; 
   constructor() public{
      storedData = 10;   
   }
   function getResult() public view returns(string memory){
      uint a = 1; 
      uint b = 2;
      uint result
      if( a > b) {   // if else statement
         result = a;
      } else {
         result = b;
      }       
      return integerToString(result); 
   }
   function integerToString(uint _i) internal pure 
      returns (string memory) {
      if (_i == 0) {
         return "0";
      }
      uint j = _i;
      uint len;
      
      while (j != 0) {
         len++;
         j /= 10;
      }
      bytes memory bstr = new bytes(len);
      uint k = len - 1;
      
      while (_i != 0) {
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      return string(bstr);//access local variable
   }
}

Run the above program using steps provided in Solidity First Application chapter.

Output

0: string: 2


In this topic we learned about Solidity – if…else statement. To know more, Click Here.

This Post Has One Comment

Leave a Reply