如需获取本内容的最新版本,请参见 Cyfrin.io 上的if / else(代码示例)
Solidity 支持条件语句 if、else if 和 else。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
contract IfElse {
function foo(uint256 x) public pure returns (uint256) {
if (x < 10) {
return 0;
} else if (x < 20) {
return 1;
} else {
return 2;
}
}
function ternary(uint256 _x) public pure returns (uint256) {
// if (_x < 10) {
// return 1;
// }
// return 2;
// 简写if/else语句的方式
// "?"运算符被称为三元运算符(或者较三目运算符)
return _x < 10 ? 1 : 2;
}
}
Remix Lite 尝试一下
END