Solidity

Solidity Scoping And Declarations

Solidity Scoping And Declarations Main Tips

  • In Solidity variables only get scoped up to their declaration on the end of the semantic block.
  • Additionally, declared variables are initialized with their default value at the beginning of the function.

Solidity Scoping And Declarations

A variable that has been declared is going to have an initial default value the byte-representation of which consists of zeros only. These “default values” of variables are the normal “zero-state” of whichever the type is. The default value of, for example, a bool is false. For uint or int types, it is 0 . In the case of statically-sized arrays, as well as bytes1 to bytes32, all individual elements will be initialized to the default value that corresponds to the type of the element. Lastly, for dynamic size arrays, string and bytes, the default value will be an empty string or array.

In Solidity variables only get scoped up to their declaration on the end of the semantic block.

Because of this, the code example bellow will not work and make the compiler to throw an error, stating “Identifier already declared :

Example

// This code does not compile because it contains illegal statements

pragma solidity ^0.4.0;

contract ErrorScoping {
    function scopeErrors() {
        uint i = 0;

        while (i++ < 1) {
            uint similar1 = 0;
        }

        while (i++ < 2) {
            uint similar1 = 0;// Being the second declaration of the variable similar1, it is illegal
        }
    }

    function minimalErrorScoping() {
        {
            uint similar2 = 0;
        }

        {
            uint similar2 = 0;// Being the second declaration of the variable similar2, it is illegal
        }
    }

    function forLoopErrorScoping() {
        for (uint similar3 = 0; similar3 < 1; similar3++) {
        }

        for (uint similar3 = 0; similar3 < 1; similar3++) {// Being the second declaration of the variable similar3, it is illegal
        }
    }
}

 

Try on Remix Try live on Hosting

Additionally, declared variables are initialized with their default value at the beginning of the function. Because of this, the code shown here is legal (it works), although very well written:

Example

pragma solidity ^0.4.0;

contract Cont {
    function func() returns (uint) {
        // baz is initialized implicitly with the value of 0
        uint bar = 5;
        if (true) {
            bar += baz;
        } else {
            uint baz = 10;// will never execute
        }
        return bar;// will return 5
    }
}

 

Try on Remix Try live on Hosting

Read previous post:
Solidity Assignment

Solidity Assignment Main Tips In Solidity assigning values to variables is a rather common task of a contract. Assignment may be a little...

Close