Solidity – if statement

Solidity - if statement

This topic is about Solidity – if statement.

The if statement is the fundamental control statement that allows Solidity to make decisions and execute statements conditionally.

Syntax

The syntax for a basic if statement is as follows −

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

Here a Solidity expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions.

Example

Try the following example to understand how the if statement works.

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 = a + b;
      return integerToString(result); 
   }
   function integerToString(uint _i) internal pure 
      returns (string memory) {
      if (_i == 0) {   // if statement
         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: 3

To know more, Click Here.

This Post Has 2 Comments

Leave a Reply