Solidity 支持 if、else if 和 else 条件语句。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract IfElse {
function foo(uint x) public pure returns (uint) {
if (x < 10) {
return 0;
} else if (x < 20) {
return 1;
} else {
return 2;
}
}
function ternary(uint _x) public pure returns (uint) {
// if (_x < 10) {
// return 1;
// }
// return 2;
// 简写 if/else 语句的方法
// "?" 操作符被称为三元运算符
return _x < 10 ? 1 : 2;
}
}代码说明:
if 语句允许您根据某些条件执行代码块。如果条件为 true,则执行代码块;否则,将跳过代码块。如果您想要添加其他选项,可以使用 else if 语句。最后,如果没有任何条件得到满足,您可以使用 else 语句。
ternary 函数演示了一种更简洁的写法,它使用了“三元运算符”。这是一种简写 if/else 语句的方式,可以让代码更加简洁易读。