this topic is about Solidity – if…else if… statement.
The if…else if… statement is an advanced form of if…else that allows Solidity to make a correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) { Statement(s) to be executed if expression 1 is true } else if (expression 2) { Statement(s) to be executed if expression 2 is true } else if (expression 3) { Statement(s) to be executed if expression 3 is true } else { Statement(s) to be executed if no expression is true }
There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.
Example
pragma solidity ^0.5.0; contract SolidityTest { uint storedData; // State variable constructor() public { storedData = 10; } function getResult() public view returns(string memory) { uint a = 1; uint b = 2; uint c = 3; uint result if( a > b && a > c) { // if else statement result = a; } else if( b > a && b > c ){ result = b; } else { result = c; } 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: 3
To know more, Click Here.
Pingback: Solidity - Decision Making - Adglob Infosystem Pvt Ltd
Really enjoyed this post.Really looking forward to read more. Great.