0
0
Blockchain / Solidityprogramming~5 mins

If-else statements in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

If-else statements help your program make choices. They let your code do different things depending on conditions.

Checking if a user has enough tokens to make a purchase.
Deciding if a transaction should be approved or rejected.
Verifying if a smart contract condition is met before executing.
Choosing different actions based on the current blockchain state.
Syntax
Blockchain / Solidity
if (condition) {
    // code to run if condition is true
} else {
    // code to run if condition is false
}
The condition is a check that results in true or false.
Use curly braces { } to group the code blocks clearly.
Examples
This checks if the balance is enough to buy something. If yes, it approves; if not, it rejects.
Blockchain / Solidity
if (balance >= price) {
    approvePurchase();
} else {
    rejectPurchase();
}
This checks if the user is the owner. Owners get access, others do not.
Blockchain / Solidity
if (isOwner) {
    allowAccess();
} else {
    denyAccess();
}
Sample Program

This smart contract checks if the balance is enough to buy an item. The buy function returns a message based on the check.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract SimpleCheck {
    uint public balance = 100;
    uint public price = 50;

    function buy() public view returns (string memory) {
        if (balance >= price) {
            return "Purchase approved";
        } else {
            return "Purchase denied";
        }
    }
}
OutputSuccess
Important Notes

In blockchain smart contracts, if-else helps control what actions happen based on conditions.

Always test your conditions carefully to avoid unexpected results.

Summary

If-else lets your code choose between two paths.

Use it to check conditions and run different code accordingly.

It is very useful in blockchain for controlling transactions and permissions.