Solidity: What is the difference between `view` and `constant`?
Solidity 0.4.16 introduced the
constantfunction modifiers. The documentation says:
constantfor functions: Same as
Does this mean
viewis just an alias for
constant? If so, why do we need it?
As I understand it, the point is that
constantis misleading (constant functions don't necessarily return constant results), and not particularly nuanced. The changes when complete will introduce two replacement keywords:
purewhich are intended to be more meaningful and useful.
From the GitHub issue,
- constant function should not modify the state (not fully enforced yet)
- constant state variable (ie. the one in the class and not in a method) is evaluated every time it is called
After the change:
- the keyword view is introduced for functions (it replaces constant). Calling a view cannot alter the behaviour of future interactions with any contract. This means such functions cannot use SSTORE, cannot send or receive ether and can only call other view or pure functions.
- the keyword pure is introduced for functions, they are view functions with the additional restriction that their value only depends on the function arguments. This means they cannot use SSTORE, SLOAD, cannot send or receive ether, cannot use msg or block and can only call other pure functions.
- the keyword constant is invalid on functions
- the keyword constant on any variable means it cannot be modified (and could be placed into memory or bytecode by the optimiser)