A function is a block of code that performs a specific task. In Solidity, functions are defined using the function
keyword followed by the function name and any parameters that the function requires. Solidity functions can be classified based on various properties, including access modifiers, input/output parameters, and function type.
The basic syntax for defining a Solidity function is as follows:
function <function_name>(<parameter_types>) <access_modifier> <function_type> returns (<return_types>) {
// Function body
}
<function_name>
is the name of the function.<parameter_types>
is a comma-separated list of the types of the function parameters.<access_modifier>
specifies who can call the function. This can be public
, private
, internal
, or external
.<function_type>
specifies the type of the function. This can be pure
, constant
, view
, or payable
.<return_types>
is a comma-separated list of the types that the function returns.Access modifiers determine who can call a function. The available access modifiers in Solidity are:
public
: Can be called from within the contract, from other contracts, and externally.private
: Can only be called from within the contract.internal
: Can be called from within the contract and from contracts that inherit from the contract.external
: Can only be called externally, and not from within the contract.Solidity functions can have both input and output parameters.
Input parameters are declared like variables and are passed to the function when it is called. For example: