DEV Community

Cover image for Scope Visibility of State Variables in Solidity
Shlok Kumar
Shlok Kumar

Posted on

Scope Visibility of State Variables in Solidity

Public variables can be accessed internally and via messages, while internal variables can only be accessed internally. Private variables are not visible to other contracts

Scope of local variables is limited to the function in which they are defined but State variables can have three types of scopes.

  • Public − Public state variables can be accessed internally as well as via messages. For a public state variable, an automatic getter function is generated.

  • Internal − Internal state variables can be accessed only internally from the current contract or contract deriving from it without using this.

  • Private − Private state variables can be accessed only internally from the current contract; they are defined not in the derived contract from it.

In Solidity, local variables have a scope that is confined to the function in which they are defined, whereas state variables might have three different scopes.

  • Public - State variables that are accessible both internally and through messages are known as public state variables. An automatic getter method is built for a public state variable when the variable is declared.

  • Internal - Internal state variables can only be accessible internally from the current contract or a contract originating from it, and they cannot be accessed externally from any other contract.

  • Private -Private state variables can only be accessed internally from the current contract in which they are defined, not from the contract derived from it. They are not accessible from any other contract.

Global Variables are Special variables that exist in the global namespace used to get certain information about the blockchain.

Important:

Solidity is a statically typed programming language, which means that the type of the state or local variable must be defined at the time of declaration. Every defined variable has a default value that is determined by the type of the variable. There is no such thing as a "undefined" or a "null."

Variables in Solidity:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Variables {
    // State variables are stored on the blockchain.
    string public text = "Hello World";
    uint public num = 69;

    function simpleFunc() public {
        // Local variables are not saved to the blockchain.
        uint i = 619;

        // Here are some global variables
        uint timestamp = block.timestamp;//Current block timestamp
        address sender = msg.sender; // address of the caller
    }
} 
Enter fullscreen mode Exit fullscreen mode

For more content, follow me at - https://linktr.ee/shlokkumar2303

Top comments (0)