Solidity - if...else 语句


“if...else”语句是控制语句的下一种形式,它允许 Solidity 以更受控的方式执行语句。

句法

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

这里评估 Solidity 表达式。如果结果值为 true,则执行“if”块中的给定语句。如果表达式为 false,则执行 else 块中的给定语句。

例子

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
   }
}

使用Solidity First Application章节中提供的步骤运行上述程序。

输出

0: string: 2
Solidity_decision_making.htm