条件语句 #

一、if语句 #

1.1 基本语法 #

solidity
if (condition) {
    // 条件为真时执行
}

1.2 使用示例 #

solidity
contract IfStatement {
    function checkPositive(int256 value) public pure returns (string memory) {
        if (value > 0) {
            return "Positive";
        }
        return "Not positive";
    }
    
    function checkEven(uint256 value) public pure returns (bool) {
        if (value % 2 == 0) {
            return true;
        }
        return false;
    }
    
    function checkAddress(address _addr) public pure returns (bool) {
        if (_addr != address(0)) {
            return true;
        }
        return false;
    }
}

1.3 单行语句 #

solidity
contract SingleLineIf {
    uint256 public value;
    
    function increment() public {
        if (value < 100) value++;
    }
    
    // 推荐:使用花括号,即使只有一行
    function incrementBetter() public {
        if (value < 100) {
            value++;
        }
    }
}

二、if-else语句 #

2.1 基本语法 #

solidity
if (condition) {
    // 条件为真时执行
} else {
    // 条件为假时执行
}

2.2 使用示例 #

solidity
contract IfElseStatement {
    function compare(uint256 a, uint256 b) public pure returns (string memory) {
        if (a > b) {
            return "a is greater";
        } else {
            return "a is not greater";
        }
    }
    
    function abs(int256 value) public pure returns (uint256) {
        if (value >= 0) {
            return uint256(value);
        } else {
            return uint256(-value);
        }
    }
    
    function max(uint256 a, uint256 b) public pure returns (uint256) {
        if (a > b) {
            return a;
        } else {
            return b;
        }
    }
}

三、if-else if-else语句 #

3.1 基本语法 #

solidity
if (condition1) {
    // 条件1为真时执行
} else if (condition2) {
    // 条件2为真时执行
} else {
    // 所有条件都为假时执行
}

3.2 使用示例 #

solidity
contract IfElseIfStatement {
    function getGrade(uint256 score) public pure returns (string memory) {
        if (score >= 90) {
            return "A";
        } else if (score >= 80) {
            return "B";
        } else if (score >= 70) {
            return "C";
        } else if (score >= 60) {
            return "D";
        } else {
            return "F";
        }
    }
    
    function compareThree(uint256 a, uint256 b, uint256 c) 
        public 
        pure 
        returns (string memory) 
    {
        if (a >= b && a >= c) {
            return "a is largest";
        } else if (b >= a && b >= c) {
            return "b is largest";
        } else {
            return "c is largest";
        }
    }
    
    function getTimeOfDay(uint256 hour) public pure returns (string memory) {
        if (hour < 0 || hour > 23) {
            return "Invalid hour";
        } else if (hour < 6) {
            return "Night";
        } else if (hour < 12) {
            return "Morning";
        } else if (hour < 18) {
            return "Afternoon";
        } else {
            return "Evening";
        }
    }
}

四、嵌套条件语句 #

4.1 基本示例 #

solidity
contract NestedIf {
    function checkNumber(int256 value) public pure returns (string memory) {
        if (value > 0) {
            if (value > 100) {
                return "Large positive";
            } else {
                return "Small positive";
            }
        } else {
            if (value < 0) {
                return "Negative";
            } else {
                return "Zero";
            }
        }
    }
    
    function validateUser(
        address user,
        uint256 age,
        bool hasLicense
    ) public pure returns (bool) {
        if (user != address(0)) {
            if (age >= 18) {
                if (hasLicense) {
                    return true;
                }
            }
        }
        return false;
    }
}

4.2 避免深层嵌套 #

solidity
contract AvoidDeepNesting {
    // 不推荐:深层嵌套
    function validateBad(
        address user,
        uint256 age,
        bool hasLicense,
        bool isVerified
    ) public pure returns (bool) {
        if (user != address(0)) {
            if (age >= 18) {
                if (hasLicense) {
                    if (isVerified) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    // 推荐:提前返回
    function validateGood(
        address user,
        uint256 age,
        bool hasLicense,
        bool isVerified
    ) public pure returns (bool) {
        if (user == address(0)) return false;
        if (age < 18) return false;
        if (!hasLicense) return false;
        if (!isVerified) return false;
        return true;
    }
    
    // 推荐:使用require
    function validateWithRequire(
        address user,
        uint256 age,
        bool hasLicense,
        bool isVerified
    ) public pure {
        require(user != address(0), "Invalid user");
        require(age >= 18, "Underage");
        require(hasLicense, "No license");
        require(isVerified, "Not verified");
    }
}

五、条件语句与三元运算符 #

5.1 三元运算符替代简单if-else #

solidity
contract TernaryVsIfElse {
    // if-else写法
    function maxValueIfElse(uint256 a, uint256 b) public pure returns (uint256) {
        if (a > b) {
            return a;
        } else {
            return b;
        }
    }
    
    // 三元运算符写法(更简洁)
    function maxValueTernary(uint256 a, uint256 b) public pure returns (uint256) {
        return a > b ? a : b;
    }
    
    // 复杂条件
    function getDiscount(
        bool isMember,
        uint256 purchaseAmount
    ) public pure returns (uint256) {
        return isMember && purchaseAmount >= 100 ? 10 : 0;
    }
}

六、实际应用示例 #

6.1 访问控制 #

solidity
contract AccessControl {
    address public owner;
    mapping(address => bool) public admins;
    bool public paused;
    
    constructor() {
        owner = msg.sender;
    }
    
    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }
    
    modifier whenNotPaused() {
        require(!paused, "Contract paused");
        _;
    }
    
    function sensitiveOperation() public whenNotPaused {
        if (msg.sender == owner) {
            // owner有最高权限
            _doSensitiveOperation();
        } else if (admins[msg.sender]) {
            // admin有部分权限
            _doLimitedOperation();
        } else {
            revert("Unauthorized");
        }
    }
    
    function _doSensitiveOperation() internal {
        // 敏感操作
    }
    
    function _doLimitedOperation() internal {
        // 有限操作
    }
    
    function setPaused(bool _paused) public onlyOwner {
        paused = _paused;
    }
    
    function setAdmin(address user, bool status) public onlyOwner {
        admins[user] = status;
    }
}

6.2 状态机 #

solidity
contract StateMachine {
    enum State { Created, Locked, Active, Completed, Cancelled }
    State public currentState;
    
    event StateChanged(State from, State to);
    
    constructor() {
        currentState = State.Created;
    }
    
    function lock() public {
        if (currentState == State.Created) {
            State previous = currentState;
            currentState = State.Locked;
            emit StateChanged(previous, currentState);
        } else {
            revert("Invalid state transition");
        }
    }
    
    function activate() public {
        if (currentState == State.Locked) {
            State previous = currentState;
            currentState = State.Active;
            emit StateChanged(previous, currentState);
        } else {
            revert("Invalid state transition");
        }
    }
    
    function complete() public {
        if (currentState == State.Active) {
            State previous = currentState;
            currentState = State.Completed;
            emit StateChanged(previous, currentState);
        } else {
            revert("Invalid state transition");
        }
    }
    
    function cancel() public {
        if (currentState == State.Created || currentState == State.Locked) {
            State previous = currentState;
            currentState = State.Cancelled;
            emit StateChanged(previous, currentState);
        } else {
            revert("Cannot cancel in current state");
        }
    }
}

6.3 支付处理 #

solidity
contract PaymentProcessor {
    enum PaymentStatus { Pending, Completed, Failed, Refunded }
    
    struct Payment {
        address payer;
        uint256 amount;
        PaymentStatus status;
        uint256 timestamp;
    }
    
    mapping(uint256 => Payment) public payments;
    uint256 public paymentCount;
    
    event PaymentCreated(uint256 indexed id, address indexed payer, uint256 amount);
    event PaymentStatusChanged(uint256 indexed id, PaymentStatus status);
    
    function createPayment() public payable returns (uint256) {
        require(msg.value > 0, "Amount must be greater than 0");
        
        paymentCount++;
        payments[paymentCount] = Payment({
            payer: msg.sender,
            amount: msg.value,
            status: PaymentStatus.Pending,
            timestamp: block.timestamp
        });
        
        emit PaymentCreated(paymentCount, msg.sender, msg.value);
        return paymentCount;
    }
    
    function processPayment(uint256 paymentId) public {
        Payment storage payment = payments[paymentId];
        
        if (payment.status == PaymentStatus.Pending) {
            if (payment.amount > 0) {
                payment.status = PaymentStatus.Completed;
                emit PaymentStatusChanged(paymentId, PaymentStatus.Completed);
            } else {
                payment.status = PaymentStatus.Failed;
                emit PaymentStatusChanged(paymentId, PaymentStatus.Failed);
            }
        } else {
            revert("Payment not pending");
        }
    }
    
    function refund(uint256 paymentId) public {
        Payment storage payment = payments[paymentId];
        
        if (payment.status == PaymentStatus.Completed) {
            payment.status = PaymentStatus.Refunded;
            payable(payment.payer).transfer(payment.amount);
            emit PaymentStatusChanged(paymentId, PaymentStatus.Refunded);
        } else {
            revert("Payment not completed");
        }
    }
}

七、最佳实践 #

7.1 使用require进行断言 #

solidity
contract RequireBestPractice {
    // 推荐:使用require
    function transfer(address to, uint256 amount) public pure {
        require(to != address(0), "Invalid recipient");
        require(amount > 0, "Invalid amount");
    }
    
    // 不推荐:使用if + revert
    function transferBad(address to, uint256 amount) public pure {
        if (to == address(0)) {
            revert("Invalid recipient");
        }
        if (amount == 0) {
            revert("Invalid amount");
        }
    }
}

7.2 保持条件简单 #

solidity
contract SimpleConditions {
    // 不推荐:复杂条件
    function complexCondition(
        address a,
        address b,
        uint256 c,
        uint256 d,
        bool e,
        bool f
    ) public pure returns (bool) {
        if (a != address(0) && b != address(0) && c > 0 && d > 0 && e && !f) {
            return true;
        }
        return false;
    }
    
    // 推荐:拆分条件
    function simpleConditions(
        address a,
        address b,
        uint256 c,
        uint256 d,
        bool e,
        bool f
    ) public pure returns (bool) {
        bool validAddresses = a != address(0) && b != address(0);
        bool validAmounts = c > 0 && d > 0;
        bool validFlags = e && !f;
        
        if (validAddresses && validAmounts && validFlags) {
            return true;
        }
        return false;
    }
}

7.3 避免重复代码 #

solidity
contract AvoidDuplicateCode {
    // 不推荐:重复代码
    function processBad(uint256 value) public pure returns (uint256) {
        if (value < 10) {
            uint256 result = value * 2;
            return result + 1;
        } else if (value < 20) {
            uint256 result = value * 2;
            return result + 1;
        } else {
            uint256 result = value * 2;
            return result + 1;
        }
    }
    
    // 推荐:提取公共代码
    function processGood(uint256 value) public pure returns (uint256) {
        uint256 result = value * 2;
        return result + 1;
    }
}

八、总结 #

条件语句要点:

语句 说明 使用场景
if 单条件判断 简单条件检查
if-else 二选一 两种情况处理
if-else if-else 多选一 多种情况处理

使用建议:

  • 使用require进行断言检查
  • 避免深层嵌套,提前返回
  • 保持条件简单清晰
  • 简单条件可用三元运算符

接下来,让我们学习循环语句!

最后更新:2026-03-27