Solidity if 语句

1. 语法

if (条件表达式) {
   被执行语句(如果条件为真)
}

2. 示例

展示 if 语句用法:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SolidityTest {
   uint storedData; 
   constructor() {
      storedData = 10;   
   }
   function getResult() public pure 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 语句
         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);// 访问局部变量
   }
}

运行上述程序,输出结果:

0: string: 3

下一章:Solidity if…else 语句

Solidity if…else 语句: 1. 语法if (条件表达式) { 被执行语句(如果条件为真)} else { 被执行语句(如果条件为假)} 2. 示例展示  if...else 语句用 ...