Folder101   Home Notes Quiz Assigns Info  
Forum Forum
101 Home 101
 
  C++ Level 2

Scope of a Variable

Introduction

Scope of a Global Variable

Scope of a Local Variable

Parameters and Scope

Extension Work


  Introduction

The scope of a variable refers to the extent to which different parts of a program have access to the variable.

  • A variable declared inside a function is different to a variable declared outside a function in that it is in effect invisible to all other functions.
  • Whereas variables declared outside all functions are visible to all functions and can be used by them.

Scope also affects a variable's creation time and lifetime:-

  • creation time - meaning when allocation of the variable in memory occurs .
  • lifetime - meaning how long the variable persists in memory and when it is deallocated from memory.

  Scope of a Global Variable

A global variable is a variable declared outside any code blocks. Usually global variable are declared at the top, just after directives and function declarations. As an example:-

int var1;  // this is a global variable

void main() {
   int var2;    // this is a local variable
}

void f() {
  var1++;
}

The scope of a global variable is the entire program. This means that a global variable is visible from within main and every other function in the program. Strictly speaking, the scope of a global variable is within the source code file that contains the variable definition.

In the example given above, var1 can be accessed from any function within the program. We can see that the it is perfectly valid for the function f to access it and change it's value.

In practice you should use global variables as little as possible. Why? For many reasons. Here are a few.

  • When creating a program you try to structure it so that each function, or module, in a program contains all the code and data it needs to do its job.
  • Global variables are a common source of bugs because their values are easily changed from anywhere within the program and may be accidentally altered.
  • It is harder to read, debug and maintain code containing lots of global variable

  Scope of a Local Variable

Just to refresh your memory, a local variable is a variable that is created inside a block of code, between opening and closing curly brackets. A local variable is only accessible from within that block. I.e.

{
   int var;
}

The variable called var is a local variable and it exists only while that block is executing. In other words, a local variable is created upon entry into a block and destroyed upon exit.

Local variables are most commonly created within blocks of code called functions. Here is one:-

void f1() {
   int var;
}

The variable created inside the f1 function called var is a local variable. It is local to the function f1. It is directly accessible only within f1. Any other function that tried to access it as so..

void f2() {
   var = 0;
}

...would produce a compiler error, informing you that var inside f2 is not declared. This is perfectly correct because var does not exist outside f1. As far as f2 is concerned var does not exist at all - ever.

We say that the scope of var is f1. It is created in memory when f1 is created. It exists only as long as f1 is executing. It is destroyed (deallocated) from memory at the same time that f1 is.

Now to be clear about the lifetime of a local variable, consider the following code:-

void main() {
   {
      int var;
   }
   var++;
}

This would produce a compiler error saying that var is undeclared. This is actually true because var is created on entry into the inner opening curly brace and destroyed upon exit. We cannot increment it outside it's block, since it no longer exists.

Here is another common mistake:-

void main() {

for (int x=0; x < 10; x++) {

   int y = x;

}

cout << y;

}

This would produce a compiler error saying that y is undeclared. This is correct because y is declared inside the for block and so does not exist outside of it.  It is created and destroyed inside the for block. In fact, y is created and destroyed 10 times in all.

Here are a few points to consider:-

  • One advantage of local variables is that memory will only be allocated to them as needed.
  • Most programmers declare all their local variables at the top of a function. This has the advantage of making code easier to read and maintain. However, you may declare a local variable anywhere within the function block.
  • Sometimes it is good practice not to declare a variable at the top of a function. For example, if a variable will only be used inside an if block, then declare it inside the if block. This saves memory because it will be destroyed on exit from the if block and not when the function ends.
  • Another advantage of local variables is that since they do not exist outside their block, they cannot be accidentally altered from somewhere else outside the block.
  • Finally you must remember that since a local variable only exists within it's block when the block ends, the variable is destroyed and it's value is lost. Consider the following code:-
  • void main() {
       int res;
       do {
          res = f ();
          cout << res;
       }while (res < 10);
    }

int f() {
      int count = 0;
      return ++count;
}

This code would produce an infinite loop because count is created and destroyed every time the function f1 is called. Since count is initialized to 0 every time, then the do-while loop never stops since res always has a value of 1 and never reaches 10.

This could be fixed a number of ways. By declaring count as a global variable or alternatively by declaring count as a static local variable.

A static local variable retains its value between function calls. It is not destroyed when the function exits. The one difference between a static local variable and a global variable is that you still cannot refer to that variable directly from a different function, so it is safer than using a global variable.

Let's have a look at the changed code:-

int f() {
      static int count = 0;
      return ++count;
}

Now count retains it's value between calls to f1 and so eventually reaches a value of 10;


  Parameters and Scope

Parameters of a function are variables that you can pass values to when you call the function. As an example, here is the function declaration for a function with 2 parameters.

func (int i, char ch);

This function has two parameters called i and ch. Parameters behave like any other local variable declared inside the function. If you like, you can think of them as special local variables, declared within a special place in the function - within the function header.

They are special because they are given their initial values when the function is called. I.e.

void main() {

  afunction( 2 , 'b' );

}

In the example, the values 2 and 'b are passed to the parameters i and ch when the function is called. In other words, the parameters i and ch are initialized to 2 and 'b' respectively on function execution.

Another phrase you might come across is the 'arguments of a function'. The arguments of a function are different to the parameters of a function, although quite often they are used interchangeably in literature.

  • The parameters of a function are the variables you are passing values to when you call the function.

 func (int i, char ch); //the parameters are i and ch in this case

  • The arguments of a function are the comma-separated list within the function call.

 func ( 2 , 'b' );  //the arguments are 2 and 'b'


  Extension Work

Carry out the following exercise:-

  1. Now start step10 of the practice assignment 3

That's it!