Photo by GuerrillaBuzz Crypto PR on Unsplash
If and else in solidity
If, else, else if explained in solidity
In this article, I will painstakingly explain what we call if, else and else if in solidity.
The first step is to declare solidity compiler version like this
pragma solidity ^0.5.0;
Now let declare the contract named Michael.
contract Michael{
}
Let create a function called Charge which accept an input of x, don't forget to set the visibility to public.
I put an underscore before x to differentiate local variable from global variable.
function Charge(uint _x) public pure returns(uint) {
}
Now the if statement.
if(_x <10){
return 1;
}else{
return 0;
}
If the inputed value from the frontend is less than 10, then it should return 1 else if the number inputed is greater than 10, then return zero. That is the meaning of the above code.
Let now see the fullcode.
pragma solidity ^0.5.0;
contract Michael{
function Charge(uint _x) public pure returns(uint){
if(_x <10){
return 1;
}else{
return 0;
}
}
}
Let make this if and else statement look more robust, mature and more sophisticated by adding else if.
To do that, the function will first look like this
function Charge(uint _x) public pure returns(string memory){
}
This means that we are returning a string and anytime string is used, you follow with storage (memory).
function Charge(uint _x) public pure returns(string memory){
if(_x <10){
return "It is less than 10";
}else if(_x <20){
return "It is less than 20";
}else{
return "It is above 20";
}
}
So if the input from frontend is less than 10, say "It is less than 10", if it is less than 20 say "It is less than 20" and if it is not captured within the if and else if, we should know that the number is above 20.
See full code below
pragma solidity ^0.5.0;
contract Michael{
function Charge(uint _x) public pure returns(string memory){
if(_x <10){
return "It is less than 10";
}else if(_x <20){
return "It is less than 20";
}else{
return "It is above 20";
}
}
}