Solidity

Variables

What are variables?

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)
  • Whole numbers, like 2, 64, and 256
  • Signed integers can be positive or negative
  • Unsigned integers can only be positive or zero, but have a larger maximum value
Floating point
  • Rational numbers, like 1.5, 2.573, and 10.0.
  • Solidity does not have floating point values implemented at the time of writing.
Boolean
bool
  • True or false.
  • Boolean values are useful in making decisions in a program.
Character
  • A single character, like ‘a’, ‘B’, and ‘@’
  • Characters are not implemented in Solidity.
String
string
  • A “string” of characters, like a word or a sentence.
  • For example, “This is a sentence” is a string.


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;
                
            
    Some things to note:
  1. All statements end with a semicolon.
  2. Types are case-sensitive. Any deviation to the type name will result in an error. For example, declaring a variable of type “Int” is illegal.
  3. Variable names are also case-sensitive. For example, “string public Name” and “string public name” are two different variables. You cannot have two variables with the same name.
  4. Variable names cannot be existing keywords in solidity. For example, “int int” is not a legal variable name.
  5. Variable names cannot start with a number. For example, “123var” is illegal, while “var123” is legal.

Note: Access modifiers will be covered in Chapter 2.

Assignment Operators

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;

Operations

In a smart contract, operations can be performed on variables, such as basic math, and comparisons.

Arithmetic

Arithmetic can be performed on integers using the arithmetic operators + - * / and %.

Arithmetic Symbol Operation
+ Addition
You can add two numbers together with +
                                
                                    int a = 5;
                                    int b = 10;
                                    int c = a + b;
                                       // c is equal to 5 + 10, or 15
                                
                            
- Subtraction
You can subtract two numbers together with -
                                int a = 5;
                                    int b = 10;
                                    int c = b - a;
                                       // c is equal to 10 - 5, or 5
                                
                            
* Multiplication
You can multiply two numbers together with *
                                
                                    int a = 5;
                                    int b = 10;
                                    int c = b - a;
                                       // c is equal to 10 - 5, or 5
                                
                            
/ Division
You can divide two numbers with /
                                
                                    int a = 5;
                                    int b = 10;
                                    int c = b / a;
                                       // c is equal to 0
                                
                            
Why is this?
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.
                                
                                    int public a = 3;
                                    int public b = 2;
                                    int public c = 3 % 2;
                                       // c = 1, since 3/2 has remainder 1
                                
                            

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.

Comparison

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.
                                
                                    int a = 5;
                                    int b = 10;
                                    bool c = a < b;
                                        // c will store true, since 5 < 10
                                
                            
< Less than
Returns true if the left operand is greater than the right operand, otherwise it returns false.

Eg.
                                
                                    int a = 5;
                                    int b = 10;
                                    bool c = a > b;
                                        // c will store false, since 5 < 10
                                
                            
<= 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
                                
                                    int a = 5;
                                    int b = 10;
                                    bool c = a <= b;
                                        // c will store true, since 5 < 10
                                
                            

Eg. 2
                                
                                    int d = 20;
                                    int e = 20;
                                    bool f = a <= b;
                                       // f will store true, since 20 is equal to 20                          
                                
                            
<= 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
                                
                                    int a = 5;
                                    int b = 10;
                                    bool c = a >= b;
                                        // c will store false, since 5 < 10
                                
                            

Eg. 2
                                
                                    int d = 20;
                                    int e = 20;
                                    bool f = a >= b;
                                      // f will store true, since 20 is equal to 20                                         
                                
                            
== Equal to
Returns true if the left operand and right operand are equal, otherwise it returns false.

Eg. 1
                                
                                    int a = 5;
                                    int b = 10;
                                    bool c = a == b;
                                        // c will store false, since 5 and 10 are not equal
                                
                            

Eg. 2
                                
                                    int d = 20;
                                    int e = 20;
                                    bool f = a == b;
                                      // f will store true, since 20 is equal to 20                                                                 
                                
                            
!= Not equal to
Returns true if the left operand and right operand are not equal, otherwise it returns false.

Eg. 1
                                
                                    int a = 5;
                                    int b = 10;
                                    bool c = a != b;
                                        // c will store false, since 5 and 10 are not equal
                                
                            

Eg. 2
                                
                                    int a = 5;
                                    int b = 10;
                                    bool c = a != b;
                                     // c will store false, since 5 and 10 are not equal                                                                                              
                                
                            

Parentheses

Similar to BEDMAS, brackets can be used to specify the order of operations.
Eg.
(3 * (4 + (5 - 6))) == 9

Decision-Making

If, else if, and else statements

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.

Content Quiz

Question Text

Loops

For Loops

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:

  1. A variable declaration - this is the counter for the for loop
  2. A condition - the for loop will repeat until this condition is false. Often, this condition revolves around the variable declared in before it
  3. A process that is performed after each iteration
                
                    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

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

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.    
                                      
                
            

Loop Control

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

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>) {

                    }                    
                
            
  1. The function declaration starts with the word “function.”
  2. Following this is the function name. Functions can be named anything within the naming restrictions for variables.
  3. Parameters are values that can be passed into a function. Not all functions require parameters, and if a function takes no parameters, the parentheses are to be left empty.
  4. Modifiers modify the properties of the function. For example, it can dictate who can call the function.
  5. A value can be returned from a function. If there is a return value, then the type of the returned value must be specified in the function header. If there is no return value,
    the “returns” portion of the function signature can be omitted.
                
                    function sum(int a, int b) public returns(int) {
                        int c = a + b;
                        return c;
                    }


                    function increment() public{
                        x++;
                    }
                
            

First Contract

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.

Coding Assessment

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.