Solidity

Solidity Constant State Variables

Solidity Constant State Variables Main Tips

  • In Solidity state variables can be declared as constant, so they have to be assigned using an expression that, at compile time, is a constant.
  • This is not yet a fully usable feature.

Solidity Constant State Variables

In Solidity state variables can be declared as constant, so they have to be assigned using an expression that, at compile time, is a constant.

Expressions accessing blockchain data (for example block.numberthis.balancenow ) or execution data (msg.gas), storage or call making to external contracts are not allowed for assignment. Expressions which might have side-effects on memory allocation are still allowed, however, these that might have side-effects on other memory objects are not allowed anyway.

Built-in functions shown in the list below are still allowed (although they make external calls to other contracts):

  • sha256
  • kecak256
  • ecrecover
  • ripemd160
  • addmod
  • mulmod 

Side-effects on the memory allocator are allowed because constructing complex objects such as lookup-tables should be possible. Keep in mind that is features is not fully usable yet.

A storage slot is not reserved by the compiler for these variables, moreover – each occurrence gets replaced with the respective constant expression (which the optimizer can compute into a single value).

Not every type for constants is implemented currently. Right now, only value types and strings are supported.

Example

pragma solidity ^0.4.0;

contract cont1 {
    uint constant a = 32**22 + 8;
    string constant myText = "text";
    bytes32 constant myHash = keccak256("text");
}

 

Try on Remix Try live on Hosting

Read previous post:
Solidity Function Modifiers

Solidity Function Modifiers Main Tips In Solidity function modifiers are used to conveniently modify function behavior. Modifiers are also inheritable...

Close