Why does this fail to compile on Solidity?

contract TestContract {
    function testFunc() {
        int256 constant testVar = 1;

It compiles if I remove the constant keyword.

3 Answers 3


In Solidity only state variables can be declared as constant.

State variables can be declared as constant. In this case, they have to be assigned from an expression which is a constant at compile time

Ref: http://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables

So just move the variable in the contract scope instead of function scope and it will work.


Because currently Solidity only accepts constant state variables for Strings and value types like in the following example:

pragma solidity >=0.4.0 <0.7.0;

contract C {
   unit constant x= 32**22 - 8;
   string constant text = "contract";

here is a link explaining variables, events & functions: https://www.bitdegree.org/learn/solidity-variables


so apparently solidity has disallowed the use of constant in functions afte version 0.5.0 this is the documentation. i have a very similar issue to yours and trying to fix it i will leave a comment here once found https://docs.soliditylang.org/en/latest/050-breaking-changes.html this is the specific page you're looking for.

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.