The constant
modifier has the meaning that the function won't modify the contract storage (but the word constant didn't actually convey the meaning that it is used for).
The new replacements for constant
after Solidity 0.4.17 release, view
and pure
, convey the meaning of their usage.
view
can be considered as the subset of constant
that will read the storage (hence viewing). However, the storage will not be modified.
Example:
contract viewExample {
string state;
// other contract functions
function viewState() public view returns(string) {
//read the contract storage
return state;
}
}
pure
can be considered as the subset of constant
where the return value will only be determined by its parameters (input values). There will be no read or write to storage and only local variables will be used (has the concept of pure functions in functional programming).
Example:
contract pureExample {
// other contract functions
function pureComputation(uint para1 , uint para2) public pure returns(uint result) {
// do whatever with para1 and para2 and assign to result as below
result = para1 + para2;
return result;
}
}
To execute/call these pure
or view
functions from outside, no transaction is needed. Just a call
is enough since the state of the blockchain is not changed by calling these. Hence no gas/ether is required for using these functions from outside.
However, internal calls to these functions may cost gas if the internal call is from a transaction. More details regrading how internal calls to these may cost gas can be found here.