Loading...
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again.
The most common way to define a function in Solidity is by using the function keyword, follow a unique function name.
Syntax:
function funciton_name(parameter-list) scope returns() {
// statement
}
Example:
pragma solidity ^0.8.0;
contract Test{
function add() public view returns(unit){
unit a=1; // local variable
unit b =1;
return a+b;
}
}
pragma solidity ^0.8.0;
contract Test{
function add() public view returns(unit){
unit a=1; // local variable
unit b =1;
return a+b;
}
function getResult() public view returns(unit){
return add();
}
In function parameter, the passed parameter can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by a comma.
Example:
pragma solidity ^0.8.0;
contract Test{
function add(uint a, unit b) public view returns(unit){
return a+b;
}
}
Function modifiers are used to modify the behavior of a function.
Example:
contract Owner {
modifier onlyOwner{
require(msg.sender == owner);
_;
}
modifier costs(unit price){
if(mag.value >=price) {
_;
}
}
}
The function body is inserted where the special symbol "_", appears in the definition of a modifier.
View functions ensure that they will not modify the state.
A function can be declared as view. The following statements if present in the function is considered modifying the state and the compiler will throw a warning in such cases.
Example:
pragma solidity ^0.8.0;
contract Test {
function getResult() public view returns(unit add){
unit a=1;
unit b=1;
add = a+b;
}
}
Output:
0: uint256: sum 2
Pure functions ensure that they are not read or modify the state. A function can be declared as pure. The following statements if present in the function is considered reading the state and the compiler will throw a warning in such cases.
A pure function can use the revert() and require() functions to revert potential state changes if an error occurs.
Example:
pragma solidity ^0.8.0;
contract Test {
function getResult() public pure returns(uint product, uint sum){
uint a = 1;
uint b = 2;
product = a * b;
sum = a + b;
}
}
Output:
0: uint256: product 2
1: uint256: sum 3