A function declaration in solidity looks like the following:
function eatHamburgers(string memory _name, uint _amount) public {
}
This is a function named eatHamburgers that takes 2 parameters: a string and a uint. For now the body of the function is empty. Note that we're specifying the function visibility as public. We're also providing instructions about where the _name variable should be stored- in memory. This is required for all reference types such as arrays, structs, mappings, and strings.
What is a reference type you ask?
Well, there are two ways in which you can pass an argument to a Solidity function:
Note: It's convention (but not required) to start function parameter variable names with an underscore (_) in order to differentiate them from global variables. We'll use that convention throughout our tutorial.
You would call this function like so:
eatHamburgers("vitalik", 100);
In Solidity, functions are public by default. This means anyone (or any other contract) can call your contract's function and execute its code.
Obviously this isn't always desirable, and can make your contract vulnerable to attacks. Thus it's good practice to mark your functions as private by default, and then only make public the functions you want to expose to the world.
Let's look at how to declare a private function:
uint[] numbers;
function _addToArray(uint _number) private {
numbers.push(_number);
}
This means only other functions within our contract will be able to call this function and add to the numbers array.
As you can see, we use the keyword private after the function name. And as with function parameters, it's convention to start private function names with an underscore (_).
To return a value from a function, the declaration looks like this: