I am just starting with solidity. I have a function like so:
function get() constant returns (uint) {
return storedData;
}
What is the use of the constant keyword here? I understand that after this keyboard we are defining the return type but why does it need constant in front of it? Are there alternatives to this such as var?
The "constant" keyword means that function will not alter the state of the contract, that means it won't alter any data, and so contract state and data remain... constant.
Such a function does not consume gas when executed by itself in your node (it may add to gas consumption if ran inside a function that alters contract state/data, because such a function call will need to be executed by miners and included in a block.
To give a little more context a constant declaration indicates that the function will not change the state of the contract (although currently this is not enforced by the compiler).
When generating the compiled binaries, declaring a function constant is reflected on the ABI. The ABI is then interpreted by web3 to figure out whether it should send a sendTransaction() or a call() message to the Ethereum node. Since calls are only executed locally, they're effectively free.
See this snippet from the web3.js library:
/**
* Should be called to execute function
*
* @method execute
*/
SolidityFunction.prototype.execute = function () {
var transaction = !this._constant;
// send transaction
if (transaction) {
return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments));
}
// call
return this.call.apply(this, Array.prototype.slice.call(arguments));
};
Calling a constant function from another contract incurs the same cost as any other regular function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With