Scope Rules in C++

Scope determines visibility of identifiers across function/procedure boundaries, code blocks and source files. The scope rules of a language decide in which part(s) of the program a particular piece of code or data item can be accessed.

There are five types of scopes in C++

Function

File

Block

Function Prototype

Class

Function Scope

Identifiers declared in the outermost block of a function have function scope. They can be accessed only in the function that declares them. Labels, which are identifiers follwed by a colon, have function scope. Labels contained in a function can be used anywhere in that function, but are not visible outside that function.

File Scope

Identifiers declared outside all blocks and functions have file scope. It can be used in all the blocks and functions written inside the file in which the variable declaration appears. These identifiers are known from their point of declaration until the end of file.

Identifiers with file scope are:

1. Global variables

2. Function definitions

3. Function prototypes placed outside all functions.

Block scope

Blocks are portions of C++ code contained within curly braces( {....} ). Identifiers declared within a block have block scope and are visible from their points of definition to the end of the innermost containing block. A duplicate identifier name in a block hides the value of an identifier with the same name defined outside the block.

A variable name declared in a block is local to that block. It can be used only in it and the other blocks contained under it.

Function prototype scope

Variables appearing in the parameter lists of function prototypes have function - prototype scope. These variables are only placeholders, no storage is allocated or reserved. they are not visible outside the function prototype. Variable identifiers in function prototypes are optional; only types are required.

Class scope

A class member is local to its class and has a class scope.

Scope of Variables

the scope of variables within a function or any other block of instructions is only the own function or the own block of instructions and cannot be used outside of them.

The scope of local variables is limited to the same nesting level in which they are declared. Nevertheless global variables can be declared that would be visible from any point of the code, inside and outside any function.

Figure illustrating the scope of variables

#include<iostream.h>

int integer; // Global variable

char aCharacter; // Global variable

char string(20); // Global variable

unsigned int number; // Global variable

main()

{

unsigned short age; // locall variable

float anumber, bnumber; // local variable

cout<<"enter your Age"; // instruction

cin>>Age; // instructions

}

HOME LEARN C++ PREVIOUS NEXT