流程控制

if else

有下面四种用法

  • if

  • if…else

  • if…else if

  • if…else if…else

用于表示条件的括号 不可以 被省略,单语句体两边的花括号可以被省略。

if

语法

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

Solidity 中非布尔类型数值不能转换为布尔类型,因此 if (1) { ... } 的写法在 Solidity 中 无效 。

例子

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

contract Demo {
    function greaterThan10(uint256 _x) external pure returns (bool) {
        if (_x > 10) {
            return true;
        }
        return false;
    }
}

if else

语法

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

例子

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

contract Demo {
    function greaterThan10(uint256 _x) external pure returns (bool) {
        if (_x > 10) {
            return true;
        } else {
            return false;
        }
    }
}

if…else if…else

语法

if (条件表达式 1) {
   被执行语句(如果条件 1 为真)
} else if (条件表达式 2) {
   被执行语句(如果条件 2 为真)
} else if (条件表达式 3) {
   被执行语句(如果条件 3 为真)
} else {
   被执行语句(如果所有条件为假)
}

例子

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

contract Demo {
    function example(uint256 _x) external pure returns (uint256) {
        if (_x < 10) {
            return 1;
        } else if (_x < 20) {
            return 2;
        } else {
            return 3;
        }
    }
}

if…else if

语法

if (条件表达式 1) {
   被执行语句(如果条件 1 为真)
} else if (条件表达式 2) {
   被执行语句(如果条件 2 为真)
} else if (条件表达式 3) {
   被执行语句(如果条件 3 为真)
} else {
   被执行语句(如果所有条件为假)
}

例子

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

contract Demo {
    function example(uint256 _x) external pure returns (uint256) {
        if (_x < 10) {
            return 1;
        } else if (_x < 20) {
            return 2;
        } else if (_x < 30) {
            return 3;
        }
        return 999;
    }
}

三元运算符

之前有介绍过三元运算符,这个相当于是 if else 的简洁版。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

contract IfElse{
    function example2 (uint _x) external pure returns (uint){
        return _x<10 ? 1 : 2;
    }
}