A variable is the simplest form of data storage in a program. Variables store a single value of a single type of data, known as a data type. These include:
Variable Type | What it holds |
---|---|
Integer (Signed and unsigned)int (signed)uint (unsigned)
|
|
Floating point |
|
Booleanbool
|
|
Character |
|
Stringstring
|
|
A variable can be declared with the format:
<type> [access modifier] name;
Eg.
int public myNumber;
uint public numSales;
bool public isValidInput;
string public user;
Note: Access modifiers will be covered in Chapter 2.
Variables can be assigned values with “=”. Variables can only be assigned values of their corresponding type.
int public num;
num = 4;
// This is an invalid statement and will cause an error.
string name = 1;
A variable can be given a value at its declaration. This is called “initialization.”
int public num = 4;
The values of a variable can be reassigned at any time.
Eg.
Int public a = 5;
a = 10;
a = 15;
In a smart contract, operations can be performed on variables, such as basic math, and comparisons.
Arithmetic can be performed on integers using the arithmetic operators + - * / and %.
Arithmetic Symbol | Operation |
---|---|
+
|
Addition You can add two numbers together with +
|
-
|
Subtraction You can subtract two numbers together with -
|
*
|
Multiplication You can multiply two numbers together with *
|
/
|
Division You can divide two numbers with /
Currently, there is no floating-point division in solidity. When dividing integers, the result always ignores the decimal. 5 / 10 is the same as 0.5, so the result ignores the .5 and returns 0. Note that division by 0 will cause an error. Division in Solidity is not well behaved in Solidity and should be avoided if possible. |
%
|
Modulo Returns the remainder of a division. Eg.
|
Applying an arithmetic operation to a variable can be shortened with arithmetic assignment operators. The statements in each row of the rightmost column are identical.
Operation | Shorthand Symbol | Equivalent Operation |
---|---|---|
Addition |
+=
|
a = a + 2; a += 2; |
Subtraction |
-=
|
a = a - 2; a -= 2; |
Multiplication |
*=
|
a = a * 2; a *= 2; |
Division |
/=
|
a = a / 2; a /= 2; |
Modulo |
%=
|
a = a % 2; a %= 2; |
Another shortcut for adding or subtracting 1 from a variable is to use ++ or –-. The following lines are identical:
// Equivalent addition statements:
a = a + 1;
a += 1;
a++;
// Equivalent subtraction statements:
a = a - 1;
a -= 1;
a–-;
Note: This only applies to adding or subtracting 1. This cannot be used to add or subtract any other number.
Variable values can be compared using comparison operators. The result of a conditional operation is a boolean.
Comparison Symbol | Operation |
---|---|
>
|
Greater than Returns true if the right operand is greater than the left operand, otherwise it returns false. Eg.
|
<
|
Less than Returns true if the left operand is greater than the right operand, otherwise it returns false. Eg.
|
<=
|
Greater than or equal to Returns true if the right operand is greater than or equal to left operand, otherwise it returns false. Eg. 1
Eg. 2
|
<=
|
Less than or equal to Returns true if the left operand is greater than or equal to right operand, otherwise it returns false. Eg. 1
Eg. 2
|
==
|
Equal to Returns true if the left operand and right operand are equal, otherwise it returns false. Eg. 1
Eg. 2
|
!=
|
Not equal to Returns true if the left operand and right operand are not equal, otherwise it returns false. Eg. 1
Eg. 2
|
Similar to BEDMAS, brackets can be used to specify the order of operations.
Eg.
(3 * (4 + (5 - 6))) == 9
If statements are useful when you want to perform certain actions if a certain (boolean) condition is true.
Each boolean condition is tested, and if the condition is true, the block associated with that condition is run.
If the first condition fails, the program checks the second, then the third, and so on.
if (<condition>) {
// Do something
}
else if (<condition>) {
// Do something
}
else {
// Do something
}
Note: Once the condition is true, every following block is ignored and the program jumps to the end of the if statement.
For loops are used when a process needs to be repeated some number of times, where the number of repetitions is known before running the program.
For loop declarations feature three distinct elements:
for (uint i = 0; i < 5; i++) {
…
}
// This loop will run 5 times, since it runs until the variable i is 5 or greater,
and after each loop, the value of i increases by 1
// i will be 0, then 1, 2, 3, 4, and following this the loop stops
While loops are used when a process needs to be repeated some number of times, where the number of repetitions is not known before running the program.
Format:
while (<condition>) {
…
}
int a = 0;
while (a < 10) {
a += 2;
}
// This program will repeat the contents of the loop until the condition is false
// Note that it is possible to create an infinite loop, where the condition is never false.
// This should be avoided, so ensure loops have an exit point.
Do-while loops are the same as while loops, except they are guaranteed to run at least once. This could be a concern if the condition in a while loop
may not be true but the program must run the contents of the loop at least once.
Format:
do {
…
} while (<condition>)
int a = 0;
do {
a += 2;
} while (a < 10);
// This loop does the same thing as the while loop example.
// The one difference is that it is guaranteed to run one iteration.
Break
- quits the current loop. Program flow will be directed to directly outside the loop, after the bottom brace
Continue
- skips the current iteration and goes to the start of the next iteration.
Functions are a series of processes performed in series.
Code executes from the top of the function down, when the end of the function is reached, program either returns value, does nothing, or returns to calling function
Function declaration format:
function functionName(<type> parameter1, <type>parameter2, …) modifiers returns(<type>) {
}
function sum(int a, int b) public returns(int) {
int c = a + b;
return c;
}
function increment() public{
x++;
}
Putting all of the concepts together, here is a contract that will increment a counter.
pragma solidity ^0.8.0;
contract Counter {
int public count;
function increment() public {
count++;
}
function setCounter(int val) public {
count = val;
}
function resetCounter() public {
count = 0;
}
}
The pragma
statement will be covered in Chapter 2, and can be ignored for now.
The body of the contract is delimited by the braces {} after our declaration of our counter contract. Contracts will also be covered in Chapter 2.
int public count;
This is a variable declaration. In this case, it will be an integer that will store the counter value for this contract.
function increment() public {
count++;
}
This is a function that takes no parameters and does not return anything. It performs one action - increment the count variable.
function setCounter(int val) public {
count = val;
}
This is another function that takes an integer to set the counter value to.
function resetCounter() public {
count = 0;
}
This function resets the value of the counter.
Write a contract that stores 2 integers which can be changed at any time, and can add, subtract, multiply, and divide the two two numbers.