36

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.

1
  • minor nitpick: do you mean to cast a float to an uint here?
    – J-B
    Commented Jul 8, 2016 at 6:38

2 Answers 2

50

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.

https://docs.soliditylang.org/en/latest/contracts.html#constant

(After following this link, you may have to click "Constant" in the left menu if the autoscroll doesn't work.)

2
  • In addition to Raine's answer, while declaring constant - you must not modify the state. Commented Jan 25, 2017 at 4:44
  • 3
    " 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
    Commented Mar 16, 2018 at 12:33
1

use constant like this in solidity:

//SPDX-License-Identifier: MIT
pragma solidity >0.8.0 <0.9.0;

// any contract can use it
uint constant pi=314; 

contract C1{
    uint constant FavorateNumber=25;
    function getNumbers() public pure returns(uint){
        return FavorateNumber*pi;
    }
}
contract C2{
    function getPi() public pure returns(uint){
       return pi;
    }
}

you can use public, external, internal, and private with variables:

  • public: anyone can get the value of a variable.

  • external: only external functions can get the value of a local variable. It is not used on state variables.

  • internal: only functions in this contract and related contracts can get values.

  • private: access limited to functions from this contract.

1
  • Jul '22: Has constant struct yet been implements ion solidity?
    – GGizmos
    Commented Jul 4, 2022 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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