Search code examples
blockchainethereumsolidityether

Why is it not possible to reassign the value in the contract level in solidity?


This is my code, I want to know the reason why I am not able to change the value in the variable a. Would you please give me the reason or any information from solidity doc?

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

contract simple {
    uint public a = 3;
    a = 16; // error occurred : parser Error expected identifier but got '='
    }

Solution

  • You are trying to change the data in the declarative part of the contract code. Put the change in the contract constructor or function.

    // SPDX-License-Identifier: MIT
    pragma solidity >=0.8.0 <0.9.0;
    
    contract simple
    {
        uint public a = 3;
    
        constructor()
        {
          a = 16; 
        }
    
        function changeData() public
        {
          a = 16;
        }
    
    }