Sub topic 10
Scope and lifetime: local, global, and static variables
This chapter assumes you can upload a sketch, that you know setup() and loop(), and that you can declare variables with basic types such as int, byte, and unsigned long. It also assumes you can print values with Serial.println(). Functions get a full chapter later, so here you only need to know that a function is a named block of code you can call.
Every variable has two properties that are easy to confuse. Scope is where in the source code the name can be used. Lifetime is how long the variable's memory exists while the program runs. Most bugs in this area come from assuming that the two always match.
The three kinds of variable
A sketch can declare variables in three places, and each place gives different behavior.
| Kind | Declared | Scope | Lifetime | Initial value if you give none |
|---|---|---|---|---|
| Global | Outside every function | The whole sketch, from the declaration down | The whole run of the program | 0 |
| Local | Inside a function or block | That block only | One execution of the block | Undefined (garbage) |
| Static local | Inside a function, with `static` | That function only | The whole run of the program | 0 |
The last row is the useful hybrid. A static local is private to one function, but it keeps its value between calls.
Global variables
A global variable is declared at the top level of the sketch, outside setup(), loop(), and any other function. Every function declared below it can read and change it.
int pressCount = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
pressCount++;
Serial.println(pressCount);
delay(1000);
}Globals exist from the moment the board starts until it is reset or powered off. That makes them the natural place for state that loop() must remember from one pass to the next. Remember that loop() returns and starts again many times. Any ordinary variable declared inside it is rebuilt on every pass.
Globals have costs:
- Any function can change them. When a value is wrong, you must search the whole sketch to find who wrote it.
- They permanently occupy RAM. On an Uno, which has 2 KB of SRAM, a global array that you only need briefly still takes its space for the whole run.
- Names can be hidden by accident (see shadowing below).
A global is declared to be visible only from the line where it appears. A function placed above the declaration cannot see it. The Arduino build tool adds function prototypes for you, but it does not move your variables.
Local variables
A local variable is declared inside a function or inside a pair of braces. Its scope is that block, from the declaration to the closing brace.
void setup() {
Serial.begin(9600);
}
void loop() {
int reading = analogRead(A0);
Serial.println(reading);
delay(500);
}Here reading is created when loop() reaches the declaration. It is destroyed when loop() returns. On the next pass a new reading is created. Nothing outside loop() can see it, and a different function can declare its own reading with no conflict.
Local variables on AVR boards such as the Uno live on the stack, a region of RAM that grows when a function is entered and shrinks when it exits. Because the memory is released on exit, locals are the cheapest way to hold temporary values. They also keep your logic easy to follow, since the value can only be changed within a few lines.
Uninitialized locals
A local variable that you do not initialize holds whatever bytes were in that memory before. This differs from globals, which the runtime sets to zero.
void setup() {
Serial.begin(9600);
}
void loop() {
int total; // not initialized: contains garbage
total += 5; // garbage + 5
Serial.println(total);
delay(1000);
}The output is unpredictable and may differ between boards, builds, or even runs. Always give a local an initial value: int total = 0;. Recent compilers warn about this when warnings are enabled in the IDE preferences.
Block scope
Braces create their own scope, not only function bodies. A variable declared in a for header or in an if body ends at the closing brace.
void setup() {
Serial.begin(9600);
for (byte i = 0; i < 3; i++) {
byte square = i * i;
Serial.println(square);
}
// i and square no longer exist here.
}
void loop() {}Using i or square after the loop gives a compile error such as 'i' was not declared in this scope. That error message is the most common sign that you used a name outside its scope.
Shadowing
If an inner scope declares a name that already exists in an outer scope, the inner one shadows the outer one. Inside the inner block, the name refers to the new variable, and the outer one is untouched.
int level = 10; // global
void setup() {
Serial.begin(9600);
}
void loop() {
int level = 0; // a new local, hides the global
level = analogRead(A0);
Serial.print("local: ");
Serial.println(level);
Serial.print("global: ");
Serial.println(::level); // the scope operator reaches the global
delay(1000);
}The global level stays at 10 forever, because the assignment changed the local. The ::level form refers explicitly to the global. Shadowing is legal and the compiler usually accepts it without complaint, so the bug appears as a value that "never updates". The simplest defense is to avoid reusing names between scopes. Some teams prefix globals, for example g_level, so the difference is visible at a glance.
Static local variables
Sometimes you want a function to remember something without exposing it to the whole sketch. Adding static to a local declaration changes its lifetime but not its scope.
unsigned int countCalls() {
static unsigned int calls = 0;
calls++;
return calls;
}
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Call number: ");
Serial.println(countCalls());
delay(1000);
}This prints 1, 2, 3, and so on. The line static unsigned int calls = 0; runs its initialization only once, the first time control reaches it. Later calls skip the initialization and reuse the existing variable. Without static, the function would print 1 every time, because calls would be recreated as 0 on each call.
The variable calls is still invisible outside countCalls(). You get the memory of a global with the privacy of a local.
A practical use: remembering the previous state
Static locals suit "what happened last time" logic, such as detecting a button press edge.
const byte buttonPin = 2;
bool buttonJustPressed() {
static bool wasPressed = false;
bool isPressed = (digitalRead(buttonPin) == LOW);
bool result = isPressed && !wasPressed;
wasPressed = isPressed;
return result;
}
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
if (buttonJustPressed()) {
Serial.println("Pressed");
}
}The function returns true only on the pass where the button changes from released to pressed. Holding the button prints the message once. wasPressed is hidden inside the function, so no other code can corrupt it.
Choosing between them
Use the narrowest scope that works.
- Start with a local. Most temporary values belong here.
- If a function must remember a value across calls and nothing else needs it, use a static local.
- If several functions share a value, or
setup()andloop()both need it, use a global.
Hardware pin numbers and fixed settings should be const globals, since a constant cannot be changed by accident. Values that are read-only are the safest kind of global.
Lifetime, memory, and `volatile`
Global and static variables are placed in a fixed area of RAM at build time. The IDE reports this after compiling: "Global variables use N bytes ... leaving M bytes for local variables." The wording matters. The number reported counts globals and statics, and the remainder is shared by the stack and any dynamic allocation. If the remainder is too small, deep function calls or large local arrays can overflow into the global data, and the board then behaves strangely or resets.
Two practical rules follow:
- Do not declare large arrays as locals inside functions that run often, unless you have checked the free memory.
- Treat the IDE's memory report as a warning when globals use more than about 75 percent of RAM on small boards.
A variable shared between normal code and an interrupt service routine needs the volatile qualifier so the compiler does not cache it in a register. That topic belongs with interrupts. It is mentioned here only because it is a scope-related decision you will meet later.
Common mistakes
- Expecting a local to persist. A counter declared inside
loop()resets on every pass. Move it to global scope or make itstatic. - Initializing a static each time. People expect
static int n = 0;to reset to 0 on each call. It does not. If you need a reset, assign explicitly:n = 0;. - Shadowing a global. Writing
int x = ...inside a function creates a new local when you meant to assign to the globalx. Drop the type name to assign:x = .... - Using a name after its block ends. This is a compile error, so it is easy to find.
- Relying on zero in a local. Only globals and statics start at zero.
- Overusing globals. A sketch where everything is global works for 30 lines and becomes hard to debug at 300.
Exercises
Exercise
A sketch declares int ticks = 0; inside loop(), then runs ticks++; and prints ticks once per second. What does it print, and give two ways to fix it so it counts 1, 2, 3, and so on?
Show answer
It prints 1 every time, because ticks is created and set to 0 on each pass through loop(). One fix is to move int ticks = 0; outside every function so it is global. The other is to declare it as static int ticks = 0; inside loop(), which keeps the value between passes and limits the scope to loop().
Exercise
In this code, what are the values printed by the two Serial.println calls, and why?
int count = 5;
void loop() {
int count = 1;
count++;
Serial.println(count);
Serial.println(::count);
delay(1000);
}
Show answer
The first call prints 2 and the second prints 5. The local count shadows the global one, so count++ changes only the local (1 becomes 2). The expression ::count names the global, which was never modified and still holds 5.
Exercise
Write a function unsigned long totalPresses() that returns how many times it has been called, but using no global variable. Which keyword makes this possible?
Show answer
Declare the counter as a static local: unsigned long totalPresses() { static unsigned long n = 0; n++; return n; }. The static keyword gives the variable a lifetime of the whole program while keeping its scope inside the function, and the initialization to 0 runs only once.