We have already had a brief introduction to variables and functions in the previous tutorial of our Blockchain Roadmap series. Today, we will discuss Variables and Data Types in Solidity in much more detail.
Variables can be thought of as reserved areas in memory that are used to store data. These variables can be of different types, depending on the type of data that is stored in them. Many programming languages support dynamic typing, wherein you can store any type of value (integer, float, boolean or string) in the variable and the compiler takes care of the rest. However, Solidity is statically typed i.e. the programmer has to specify the data type of the variable in the code itself.
Data types in Solidity
A variable of the Boolean data type can store either of the two values, true or false. Boolean variables can be used to store conditional values to trigger sections of code accordingly. The following is an example of how to declare a Boolean variable.
The integer data type is widely used for implementing mathematical operations in smart contracts. There are two types of integers: signed and unsigned.
- Signed: Signed integers can be assigned any numerical value. Signed integers are declared as int.
- Unsigned : Unsigned integers can only be assigned positive numerical value. Unsigned integers are declared as uint.
There are different sizes of integers like uint8, uint16, uint32….uint256, etc. The programmer can choose the size according to the requirement of the code. By default, a variable declared as uint/int without specifying its size corresponds to uint256.
The address data type is used to store Ethereum addresses in variables. The size of these addresses is 20 bytes, the same as Ethereum addresses. The address type also has a global variable ‘address’, that has the following members: address.balance, address.call, address.send. address.transfer, etc.
The String data type is used to store text i.e. alphanumeric literals. We have used the string data type in the previous tutorial where we wrote our first Solidity Smart Contract. Strings are enclosed in single or double quotes.
Bytes give a binary representation of data in smart contracts. An advantage of bytes over string is that bytes are considerably cheaper at saving data than strings. You can declare bytes as [bytes1, bytes2, bytes3,….bytes32]. Bytes should be used for contract-to-contract relations, as strings can cause problems.
Arrays are used to store a series or collection of objects all of which are of the same size and type. Each object in an array is called as an array element. The elements of array can be accessed by their index. Array indices in Solidity start at 0. So, in order to access an array element at position 4, you have to refer to the index 3.
Array also has some members built into it like array.length, array.push, array.delete, etc.
In the next tutorial, we will study the different type of functions in Solidity.