In Solidity, a function is a group of reusable code which can be called anywhere in the program.
A function is a collection of reusable code that may be invoked at any point in your program's code. This reduces the need to rewrite the same code over and again in different places. It assists programmers in the creation of modular code. Functions enable a programmer to break down a large software into a number of smaller and more manageable functions.
Solidity, like any other advanced programming language, provides all of the tools required to construct modular code using functions, just like any other advanced programming language would. This section teaches how to create your own functions in Solidity using the Solidity language.
Definition
It is necessary to declare a function before it may be used. Defining a function in Solidity is most commonly done by referencing it with the function keyword, followed by a unique function name, a list of parameters (which may or may not be empty), and a statement block enclosed by curly brackets.
Syntax
The basic syntax is shown here:
function function-name(parameter-list) scope returns() {
//statements
}
Example:
pragma solidity ^0.8.0;
contract Test {
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return result;
}}
Visibility
Solidity distinguishes between two types of function calls: external function calls that generate an actual EVM message call and internal function calls that do not. Furthermore, internal functions can be rendered inaccessible to derived contracts by modifying the contract's structure. There are four different types of visibility for functions as a result of this.
External functions are included in the contract interface, which means that they can be called from other contracts as well as from transactions. An external function f cannot be called from within another function (for example, f() does not work, but this.f() does work).
Public functions are an element of the contract interface and can be called either internally or via message calls. They are called by the contract interface.
Internal functions can only be accessible from within the current contract or from contracts that are derived from it, and not from outside of it. They are not accessible from the outside world. The fact that they are not available to the outside world through the contract's ABI means that they can take parameters of internal types such as mappings or storage references.
Private functions are similar to internal functions, with the exception that they are not visible in derived contracts.
For more content, follow me at - https://linktr.ee/shlokkumar2303
Top comments (0)