Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Local and Global Variables

Nearly every programming language has a concept of local variable. As long as two functions mind their own data, as it were, they won’t interfere with each other.

That’s definitely a factor in the previous example (Example 4.2). Both main and prime have a local variable named i. If i were not local—that is, if it was shared between functions—then consider what could happen.

First, the main function executes prime as part of evaluating the if condition. Let’s say that i has the value 24.

if (prime(i))
    cout << i << " is prime" << endl;
else
    cout << i << " is not prime" << endl;

The value 24 is passed to the prime function.

// Assume i is not declared here, but is global.

int prime(int n) {

    for (i = 2; i <= sqrt((double) n); i++)
        if (n % i == 0)
            return false;

    return true;   // If no divisor found, n is
prime.
}

Look what this function does. It sets i to 2 and then tests it for divisibility against the number passed, 24. This test passes—because 2 does divide into 24 evenly—and the function returns. But i is now equal to 2 instead of 24.

Upon returning, the program executes

cout << i << " is not prime" << endl;

which prints the following:

2 is not prime

This is not what was wanted, since we were testing the number 24!

So, to avoid this problem, declare variables local unless there is a good reason not to do so. If you look back at Example 2.3, you’ll see that i is local; main and prime each declare their own version of i.

Is there ever a good reason to not make a variable local? Yes, although if you have a choice, it’s better to go local, because you want functions interfering with each other as little as possible.

You can declare global—that is, nonlocal—variables by declaring them outside of any function definition. It’s usually best to put all global declarations near the beginning of the program, before the first function. A variable is recognized only from the point it is declared, to the end of the file.

For example, you could declare a global variation named status:

#include <iostream>
#include <cmath>
using namespace std;

int status = 0;

void main () {
      //
}

Now, the variable named status may be accessed by any function. Because this variable is global, there is only one copy of it; if one function changes the value of status, this reflects the value of status that other functions see.

  • + Share This
  • 🔖 Save To Your Account