Writing functions in solidity
A function is a unit of code designed to do a particular task within a larger contract. In this recipe, you will learn about creating and interacting with functions in solidity.
How to do it...
- Create a function in solidity with the
function
keyword to perform a specific task. The following example demonstrates how we can create a simple function:
contract Test { function functionName() { // Do something } }
Create another function to accept input parameters. These parameters can be declared just like variables. The following example accepts two parameters of type
uint
:
contract Test { function add(uint _a, uint _b) public { // Do something } }
- Define output parameters with the same syntax. The
returns
keyword is used to specify the return. The following function returns a variable of typeuint
:
contract Test { function add(uint _a, uint _b) public pure returns (uint sum) { sum = _a + _b; } }
- Declare
return...