Lesson 9: Variables and Scope


Introduction

So far, we have been exposed to the following data types

  • short
  • int
  • long
  • float
  • double
  • char
  • boolean

 

What is a variable?

A variable is a symbolic name for some piece of data or value. A variable “stands in” for possible values and can change values during the execution of a computer program.

 

What is a function?

Functions are self-contained pieces of code that accomplish something specific. Functions can be thought of as a “mini-program”.

 

Variables and Variable Scope

Variables are the names for some piece of data. Take for example, a = 2. The variable is “a” and the value that is assigned to “a” is “2″.

Variables, in computer science, can be named almost anything you want. Variables are also associated with a data type, which describes what kind of value it can hold (integer, decimal, boolean, character, etc).

Up until now, we have used and defined variables outside and inside our functions called void loop() and void setup(). Now, let’s go another step and learn how variables work:

Two kinds of variables (do not confuse this with data type):

  1. Local Variables
  2. Global Variables

Local Variables are variables that are defined inside a function or a block of code (i.e. between brackets the ( ) or { } ). They can only be used by statements that are inside that function or block of code. Local variables cannot be accessed outside and are only known within its “local” area.

{
 int i = 0; // local variable, only available to be used within the {}
 for (i = 0; i < 10; i++) {
 Serial.println("The value of i is " + i);
 }
}

 

Global Variables are variables that are defined and can be used anywhere in your program. You can access the variable’s value, change the value and use it anywhere throughout your code. They are usually defined at the very top of your program.

int pbPin = 5; // Global variable, can be used anywhere
int ledPin = 6; // Global variable, can be used anywhere

void setup() {
 pinMode(pbPin, INPUT);
 pinMode(ledPin, OUTPUT);
}

void loop() {
 while (digitalRead(pbPin) == LOW) {
 digitalWrite(ledPin, HIGH);
 delay(50);
 digitalWrite(ledPin, LOW);
 delay(50);
 }
}

 

A Local Variable and a Global Variable can have the same name, but the value of the local variable takes precedence.

 

When do we use Local versus Global variables?

There is no hard rule for when to use a global variable versus a local variable. Many programmers will avoid using Global variables because it is very easy to “contaminate” or otherwise inadvertently change a global variable’s value by mistake.

You can use Global variables to make things easier to pass values between functions within your program, but it can be easy to get into a lot of trouble if you modify Global variables all the time. It may get hard to track down potential bugs in your program.