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.

Raine Revere
  • 3,600
  • 2
  • 23
  • 34

2 Answers2

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.)

Raine Revere
  • 3,600
  • 2
  • 23
  • 34
  • In addition to Raine's answer, while declaring constant - you must not modify the state. – Ashok Mahalik Jan 25 '17 at 04: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 Mar 16 '18 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.

aakash4dev
  • 691
  • 3
  • 11