Functions
Learn about Solidity
In this section, we will look at functions. Recall from the beginning of this course that all smart contracts consist of a state and their behaviors. With regards to the latter, functions allow us to define the behavior of a smart contract.
Structure of a Function
Similar to other programming languages, all functions consist of two sections: their header and their body. An example of the following can be found below:
In the above, we have the code function getOne() public pure returns(uint) as the header of the function, while the code return 1; is the body of the function (the body of a function is always encapsulated by curly brackets).
Function Header
Focusing first on the header of a function, below is the required syntax that all function must have:
In the parentheses, we list the parameters of the function. In addition to having a name, each parameter of a function must also be marked with its type. The only concept that might be new for most developers is the visibility of a function. In Solidity, we can mark a function with the following visibility traits:
- Public
- Private
- Internal
- External
Function Body
As of right now, the only thing we know what to do inside the body of a function is declaring/defining local variables. Inside the bodies of functions, we can also use regular mathematical operations like in other programming languages; the following code demonstrates this: