# Global and Local variables.

## Local variables

Local variables must always be defined at the top of a block.

C++ has changed the rules regarding where you can define a local variable. Click here for the low down.

When a local variable is defined - it is not initalised by the system, you must initalise it yourself.

A local variable is defined inside a block and is only visable from within the block.

       main()
       {
           int i=4;
           i++;
       }

When execution of the block starts the variable is available, and when the block ends the variable 'dies'.

A local variable is visible within nested blocks unless a variable with the same name is defined within the nested block.

       main()
       {
           int i=4;
           int j=10;

           i++;

           if (j > 0)
           {
              printf("i is %d\n",i);      /* i defined in 'main' can be seen      */
           }

           if (j > 0)
           {
              int i=100;                  /* 'i' is defined and so local to
                                           * this block */
              printf("i is %d\n",i);
           }                              /* 'i' (value 100) dies here            */

           printf("i is %d\n",i);         /* 'i' (value 5) is now visable.        */
       }

## Global variables

C++ has enhanced the use of global variables.

Global variables ARE initalised by the system when you define them!

Data Type | Initialser
int | 0
char | '\0'
float | 0
pointer | NULL

In the next example i is a global variable, it can be seen and modified by main and any other functions that may reference it.

       int i=4;

       main()
       {
           i++;
       }

Now, this example has global and Internal variables.

       int i=4;          /* Global definition   */

       main()
       {
           i++;          /* global variable     */
           func
       }

       func()
       {
           int i=10;     /* Internal declaration */
           i++;          /* Internal variable    */
       }

i in main is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global.

static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.

## Example:

An Example program.

## See Also:

See Storage classes to see the more powerfull features of variable declarations.

Top | Master Index | Keywords | Functions