Learn Solidity: Scoping and Declarations in Solidity

In this post, we will understand the scoping & declaration of variables in Solidity Language.

Advertisements
World is looking for a Certified Blockchain Expert Become one

Notice: This is one of the multi-post series of Learn Solidity - Build Decentralized Application in Ethereum. This is an attempt to teach you all about Solidity - A Programming Language for Ethereum Based Smart Contracts. If you want to take this as a video course please signup using below button.
pragma solidity ^0.4.0;

// A variable which is declared will have an initial default value whose byte-representation 
// is all zeros. The “default values” of variables are the typical “zero-state” of whatever 
// the type is. For example, the default value for a bool is false. The default value for 
// the uint or int types is 0. For statically-sized arrays and bytes1 to bytes32, each 
// individual element will be initialized to the default value corresponding to its type. 
// Finally, for dynamically-sized arrays, bytes and string, the default value is an 
// empty array or string.

// A variable declared anywhere within a function will be in scope for the entire function, 
// regardless of where it is declared. This happens because Solidity inherits its scoping 
// rules from JavaScript. This is in contrast to many languages where variables are only 
// scoped where they are declared until the end of the semantic block. As a result, 
// the following code is illegal and cause the compiler to throw an error, Identifier already declared:

contract ScopingErrors {
    function scoping() {
        uint i = 0;

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

        while (i++ < 2) {
            uint same1 = 0;// Illegal, second declaration of same1
        }
    }

    function minimalScoping() {
        {
            uint same2 = 0;
        }

        {
            uint same2 = 0;// Illegal, second declaration of same2
        }
    }

    function forLoopScoping() {
        for (uint same3 = 0; same3 < 1; same3++) {
        }

        for (uint same3 = 0; same3 < 1; same3++) {// Illegal, second declaration of same3
        }
    }

    function foo() returns (uint) {
        // baz is implicitly initialized as 0
        uint bar = 5;
        if (true) {
            bar += baz;
        } else {
            uint baz = 10;// never executes
        }
        return bar;// returns 5
    }
}
Previous: Control Structure in Solidity Next: Input and Output Parameters in Solidity