State variables are variables declared at the beginning of the contract, outside the scope of local variables declared in function.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.0 <0.9.0;
contract SimpleStorage {
uint public storedData; // State variable
// ...
function updateStoredData(uint newData) public {
uint formattedData = newData * 2; // formattedData is local variable
storedData = formattedData;
}
function getFormattedData() public view returns (uint) {
return formattedData; // failed can't compile because formattedData is local scope to the other function
}
function getStoredData() public view returns (uint) {
return storedData; // can compile because global variable
}
}
Functions
Function are functions declared to perform calculations, change the value of variables, etc. A sample function is given below.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.1 <0.9.0;
contract SimpleAuction {
function bid() public payable { // Function
// ...
}
}
// Helper function defined outside of a contract
function helper(uint x) pure returns (uint) {
return x * 2;
}
Function modifiers
Function modifier are declarations for function to create conditions for running actions of that function.