Lifetime and Scope

Lifetime

Lifetime of a variable is the period of time during which the value exists in memory.

Scope

Scope of a variable is the region of code in which the variable name is usable.

A variable in scope may be temporarily "hidden" when an inner scope declare a variable with the same name.

int i = 12;	// a variable named i
printf("i before loop: %d	", i);
for (int i = 0; i < 1; i++) { 	// a new variable named i
	printf("i inside loop: %d	");
}
printf("i after loop: %d	", i);	// the old i

Output:

i before loop: 12	i inside loop: 0	i after loop: 12

The variable foo takes precedent.

Types of Variables

Local ("stack") variables are alive from the point of declaration until end of block in which declared.

Static variables (declared using the static keyword) have similar scope to local variables, but have a longer lifetime.

Global variables (declared outside any function; right under the headers) are automatically created at program start and initialized to zero(!).

Where are they stored?

Local variables are stored in a region of memory known as the stack.

Both static and global variables live in a region of memory known as the data segment.

Dynamically-allocated memory lives in a third region of memory, called the heap.