solidity – How to Update a Storage Variable in Solidity

solidity

I am new in Solidity, please advise.

I have a code

    uint public bal = address(this).balance;
    
    function getBalance() public view returns (uint) {
            return address(this).balance;
    }

bal variable is 0 by default. I sent 10 Wei to the contract and when I check the bal again – it is still 0. I check the balance with getBalance() function and it shows
10 as expected. Why bal was not updated even it was stated as a global variable? Thank you!

Best Answer

Variable bal is returning zero, because at the time of declaring this variable the contract balance was zero. This variable is stored in the state of the contract and it is not dynamically reading the current contract balance.

If for whatever reason you need bal variable to be up to date with the contract balance then on each address(this).balance call you will have to update bal value as well.

Related Topic