条件判断

if 判断

Solidity 中的 if 语法与 C++JavaScript 等大括号语言相同:

If.sol
运行
复制
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;

contract If {
    function test(int n) public pure returns (string memory) {
      // 基本使用
      if(n == 1) {
        return "A";
      }

      // 单语句可省略花括号
      if(n == 2) return "B";

      // if-else 形式
      if(n == 3) return "C";
      else return "D";

      // 非法,1 为 int 型,无法转换为布尔型
      // if(1) return "E";
    }
}

三元操作符

Solidity 还支持三元操作符,其语法为:<布尔表达式> ? B : C。当布尔表达式为真是,取 B,否则取 C

TernaryOperator.sol
运行
复制
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;

contract TernaryOperator {
    /// @notice 判断是否为偶数
    function isEven(uint n) public pure returns (string memory) {
      return n % 2 == 0 ? "n is even" : "n is odd";
    }
}