Variables in Solidity smart contracts

Variables in Solidity smart contracts are used to store information. Think of variables as containers that hold information for use throughout your program. They also help with labeling this stored data with descriptive names to make your code easier to read.

Solidity supports several types variables in Solidity smart contracts.. These variable types are:

  • State Variables
  • Local Variables
  • Global Variables

State Variables in Solidity

  • State variables are permanent and stored on the blockchain in contract storage.
  • Declared outside of a function and stored on the blockchain
  • Stored on the blockchain in the order of declaration

pragma solidity ^0.5.0;

contract SampleContract {

    //state variable of data type unint declared called "storedData"
    //Data in this variable will be saved to the block chain
    uint storedData; 

}

Local Variables in Solidity

  • Are declared in a function and used in the function they are referenced in
  • Local variables are temporary and not stored on the blockchain in contract storage.
  • Usually these are the variables that we create temporarily to hold values in calculating or processing something
  • Local variables of array, mapping or struct type reference storage by default

pragma solidity ^0.5.0;

contract SampleContract {


   function getResult() public view returns(uint){

      //local variable
      uint a = 7;
      //local variable 
      uint b = 3;
      uint result = a + b;
      //access the local variable
      return result; 
   }
}

Global Variables in Solidity

Global variables exists in the global namespace and are used to retrieve information about the blockchain. Read the Docs for an up to date list of Global Variables. Some examples of Global variables are:

  • block.difficulty – Current block difficulty
  • block.number – Current block number
  • block.timestamp – Current block timestamp

Rules

Consider the following Solidity variable naming conventions:

  • Variable names in Solidity are case sensitive. For example, Bob and bob are two different variables
  • You should not use any of the Solidity reserved keywords as a variable name. For example boolean or bool variable names are not valid.
  • Solidity variable names should not start with a number (0-9). They must begin with a letter or an underscore character. For example, 789Bob is an invalid variable name but _789Bob is a valid variable name

Make your contract easier to read

Tip – Use a naming convention in your code to differentiate state variables from local variables. This will make your code easier to read. For example have all of your state variables start with “s_” (s_stateVariableName) and your contract will be easier to read.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – Functions in a Solidity smart contract

Ledger Nano X - The secure hardware wallet