Variables must be declared before they can be used in C++. This is why a lot of developers follow the best practice of defining the variables at the top of a function.
Variable Scope
By default variables can be used in the function that they are created. This is their scope, is is often referred to as local scope.
However, in C++, it’s a little more complicated. As a variable can be accessible, i.e. in scope, only within the braces that it is created, or within a child set of braces.
So for example, a variable defined in a function, either as a parameter or declared locally, can be used inside of an if block within that function. But a variable defined within an if block, cannot be used outside of the if block in the function that it exists.
int x = 10;
if( 11 < 22 )
{
int y = x; // this is legal
x += 10; // this is legal
}
cout << y << endl; // this is not right. The variable y is out of scope.
The For Loop Scope
A minor note, is that a variable defined in the for initialization phase is accessible inside the for block, but not outside. This is treated as a special case, and handled in such a manner.
You can define a variable before the for loop, so that it is accessible outside of the for body however.
for(int i = 0; i < 5; i++)
{
cout << i << endl;
}
cout << i << endl; // error - variable is out of scope since it was created in the for loop initialization phase.
int j;
for(j = 0; j < 5; j++)
{
cout << j << endl;
}
cout << j << endl; // this is legal since j was defined outside of the for loop
Global Variables
For a variable to be global, it just needs to be defined outside of a function. A global variable is accessible globally, that means from any function.
While this might make coding “easier” it brings about issues with identifying why a variable changed, which function changed, and is it being used for the right purpose.
For that reason, we try to avoid using global variables when ever possible.
Note: The exception to this is when you create a constant. Since it cannot change, we often define those outside of our function, so any function can use the value.
const double PI = 3.1415; // this is OK
double radius = 10; // this shouldn't be done
int main()
{
// do stuff
}
Static Local Variables
Normally when a function ends, your variable values are lost. Calling a function again causes the values to be reset.
However, that is normally. If you put the keyword static
before the variable definition, it will retain the value when you come back to the function.
When you initialize it, the value is set the first time, after that, it was the last value set.
void counter();
int main()
{
counter();
counter();
counter();
return 0;
}
void counter()
{
static int x = 1;
int y = 1;
x++;
y++;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
}
Local, Global, and Static Variables in C++ was originally found on Access 2 Learn