Main Content

Variable Scope in C++

Archive - Originally posted on "The Horse's Mouth" - 2009-01-22 14:19:40 - Graham Ellis

In C++, a variable is 'scoped' to the block in which it is declared. In other words, it exists from the point at which you tell the compiler what type of value it contains through to the close brace at that matches the open brace preceeding that declaration.

In the most frequent use, this means that a variable defined inside a loop doesn't exist after the loop has been exited. And that's very useful indeed in clearing down temporary memory storage for use within the loop's iterations. If you should happen to have another variable of the same name in the outer code (usually a daft thing to do!), its contents will NOT be visible within the inner block as they'll be masked by the more local variable, but they will be unmasked after the outer block is exited.

You can even set up a block that's not a loop and not a conditional - that's there purely to scope variables - if you wish. Simply use a pair of culry braces without any if, while or other keyword. Here's a code example that demsonstrates these features:

#include <iostream>
using namespace std;
 
int main () {
   int demo[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
   int k;
 
   int answer = 42;
 
   for (k=0; k<12; k++) {
 
      int answer = demo[k]; /* masks the original answer */
      cout << answer << ", ";
      }
 
   cout << endl << "hidden was " << answer << endl;
 
   { /* This block is only for scoping purposes */
   float answer = 3.1415;
   cout << answer << " is something to do with cherry pie" ;
   }
 
   cout << endl << "hidden was " << answer << endl; /* the original again */
}


When I run that code, my results look like this:

[trainee@easterton lp]$ ./vscpp
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
hidden was 42
3.1415 is something to do with cherry pie
hidden was 42
[trainee@easterton lp]$