18

Can you declare a constant variable in Solidity?

const uint answer = 42;

Or is the only way to do it with a const function?

function GetAnswer() constant returns(uint ret) {
  return 42;
}

I know you could always create a normal public variable and then just not have any setters in the code, but this is not immediate obvious from the declaration, so it seems preferable to explicitly declare a variable as a constant or read-only if the language supports it.

  • minor nitpick: do you mean to cast a float to an uint here? – Joris Bontje Jul 8 '16 at 6:38
28

Found the answer:

State variables can be declared as constant (this is not yet implemented for array and struct types and not possible for mapping types).

contract C {
    uint constant x = 32**22 + 8;
    string constant text = "abc"; 
}

This has the effect that the compiler does not reserve a storage slot for these variables and every occurrence is replaced by their constant value.

The value expression can only contain integer arithmetics.

http://solidity.readthedocs.io/en/latest/contracts.html#constants

  • In addition to Raine's answer, while declaring constant - you must not modify the state. – Ashok Mahalik Jan 25 '17 at 4:44
  • " the compiler does not reserve a storage slot for these variables" - does it mean we pay no gas for constants? 1 byte is 1 gas, so if I use a constant that normally takes 5 bytes we pay no gas. Is it right? – Dany D Mar 16 '18 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.