# Variables

## Introduction

Computer Architecture has gone through enormous changes in the past 50 years but one element remained unchanged, the Von Neumann concept of computer design.

Its ability to treat instructions as data is what makes assemblers, compilers, linkers, loaders, and other automated programming tools possible. It makes “programs that write programs” possible. This has made a sophisticated self-hosting computing ecosystem flourish around von Neumann architecture machines.

We will focus on the memory component in this writing, a deep understanding for this part is essential to the reliability of any software application you write. It has been said that the vast majority of all software crashes is due to memory and their leakages.

Associated with every variable created in memory are many information, but for the purpose of this article we will focus only on three of them, symbol name, type of variable, and the address of the variable usually written in hexadecimal.

Declaring variables in Swift is as simple as the following few lines

let number1 : Int = 45
let number2 = 70
var sum : Int


On the current stack frame main we have create three variables as follows:

each variable has a location referenced by name. Performing a simple operation

sum = number1 + number2


Will result in the following

The type of the variables are important, here all three variables have the type Integer so no conversion was necessary.

## Passing Variables

Moving further we will define function swap which swaps two integers passed to it

func swap(_ a:  Int, _ b:  Int) {
let hold = a
a = b
b = hold
}


Function swap expects two parameters when invoked by the caller, unlike languages C or C++, Swift will not compile this code since a and b are constants by default hence their values can not be changed.

In C or C++ this code would compile perfectly and execute but the result would not be what the user expected. Swift safety features helps here and the compiler would prevent compiling the code.

Fixing the problem would require to add the inout keyword as follows

func swap(_ a: inout Int, _ b: inout Int) {
let hold = a
a = b
b = hold
}


Invoking swap would require passing the address of the variable denoted by the & operator

swap(&number1, &number2)


Here the parameters a and b would be aliases for number1 and number2, any modification to a or b on the swap frame would modify number1 and number2 on the main frame, the following would illustrate

Here it can be seen that any modification on the swap frame to a or b would effect the corresponding variables on the main frame. This can be easily seen on the Xcode debugger, where the frame is shown on the left panel and the variables address and values are shown in the panel at the bottom.

Variables are the essential part of any Von Neumann architecture computer, understanding them will make your life easier to avoid irrational behavior from your application.

Til next time, happy coding!

1313