C++ Builder Tutorials

C++ Builder: Scope of Variables

A scope is a region of the program.

There are two places where variables can be declared:

  - local variables are declared inside a function or code block;
    "formal" parameters act as local variables, they are declared in the definition of a function;
  - global variables are declared outside of all functions.


Local variables

Variables that are declared inside a function or code block are local variables.
They can be used only by statements that are inside that function or block.
A local variable is not initialized by the system, you must initialize it yourself.

Example:

#include...
 
int SomeFunction()
{
  int G = 0;  // initialize a local variable before using it 
  ... 
}

Global variables

Global variables are defined outside of all the functions, usually near the top of a unit.
Global variables can be accessed from anywhere in the program.

Global variables are initialized automatically by the system when you define them as follows:

Data type:     initialized to:

int 	       0
char           '\0'
float          0
double         0
pointer        NULL

Example:

#include...

// Global variable declaration:
int g;  // g is automatically initialized to 0 

A local variable can have the same name as a global variable, but inside a function the local variable has priority. Example:

#include...
 
// Global variable declaration:
int g = 20;
 
int SomeFunction()
{
  // Local variable declaration:
  int g = 10;
  int a;
  a = g;  //  a will become 10
  return a; 
}