Conditional statements in Solidity allow developers to execute specific blocks of code based on certain conditions. They are essential for controlling the flow of a program and making decisions within smart contracts. The primary conditional statements in Solidity include if, if-else, else if, and require.

1. If Statement

The if statement executes a block of code if the specified condition evaluates to true.

Sample Code for If Statement


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

contract IfExample {
uint256 public value;

function setValue(uint256 newValue) public {
if (newValue > 0) {
value = newValue; // Set value if newValue is greater than 0
}
}
}

2. If-Else Statement

The if-else statement allows developers to execute one block of code if the condition is true and another block if it is false.

Sample Code for If-Else Statement


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

contract IfElseExample {
uint256 public value;

function setValue(uint256 newValue) public {
if (newValue > 0) {
value = newValue; // Set value if newValue is greater than 0
} else {
value = 0; // Set value to 0 if newValue is not greater than 0
}
}
}

3. Else If Statement

The else if statement allows for multiple conditions to be checked sequentially. If the first condition is false, it checks the next condition, and so on.

Sample Code for Else If Statement


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

contract ElseIfExample {
string public status;

function checkValue(uint256 value) public {
if (value > 100) {
status = "High"; // Set status to "High" if value is greater than 100
} else if (value > 50) {
status = "Medium"; // Set status to "Medium" if value is greater than 50
} else {
status = "Low"; // Set status to "Low" if value is 50 or less
}
}
}

4. Require Statement

The require statement is used to enforce certain conditions before executing further code. If the condition evaluates to false, the transaction is reverted, and an error message is returned. This is often used for input validation.

Sample Code for Require Statement


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

contract RequireExample {
uint256 public value;

function setValue(uint256 newValue) public {
require(newValue > 0, "Value must be greater than 0"); // Check that newValue is greater than 0
value = newValue; // Set value if condition is met
}
}

Conclusion

Conditional statements are vital for controlling the logic flow in Solidity smart contracts. By using if, if-else, else if, and require, developers can implement decision-making processes that enhance the functionality and security of their contracts. Understanding how to effectively use these statements is crucial for writing robust and efficient Solidity code.