9

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?

Kex
  • 8,023
  • 9
  • 56
  • 129

2 Answers2

15

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.

  • Excellent! Thanks for your answer. – Kex Aug 25 '17 at 03:47
  • 1
    What about function `set(uint x) { storedData = x; }` what would happen if I add the keyword constant to this? Why does the `get` need the word constant? Would it cost gas if omitted even though it doesn't modify data? – Kex Aug 25 '17 at 03:50
  • 3
    "constant on functions used to be an alias to view, but this was dropped in version 0.5.0." https://docs.soliditylang.org/en/v0.8.10/contracts.html#function-modifiers – elpddev Mar 08 '22 at 15:22
3

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.

Yao Sun
  • 31
  • 2
  • If it incurs the same cost, why do I need it then? Why is it used in the `ERC20 balanceOf()` function? the function only returns `return balances[_owner];` and changes no state. Where is the sense of it? – sunwarr10r Nov 10 '17 at 16:41
  • just to be more clear, is it not better a developer uses the view modifier for a function instead of constant as view function ensures that the state of the contract is not altered & it also enforces that – Nature Jul 03 '22 at 23:42