If you like my posts please leave a comment.

Monday, December 3, 2012

Scope Rules in C++


Scope Rules In C++:

By now we have learned how to declare an UDF (User Defined Function), how to define them, how to call them, what is return type of a function, how to pas & return a value from a function, how to pass & return a reference from a function and how to pass and return pointer from the function, etc.
            While working with the functions so for, in many occasions we have declared variables in different segments of the program. Some time just after the header files mentioned, or sometimes inside the main() function or sometimes in function header or sometimes inside a function body or even sometime declared variables as loop variables. Now the question is – Do declaration of variable(s) in different segments of a program create any difference? Answer to this question you will get after going through the discussion that follows:
            Now in this segment of discussion we will talk about SCOPE RULES. The scope rule of a particular programming language are the rules that decide, in which part(s) of the program a particular piece of code or data item would be known and can be accessed.


            Thus – The program part(s) in which a particular piece of code or data item can be identified and accessed is known as piece-of-code’s or variable’s scope.
            C++ has four kinds of scope:

Local Scope.

An identifier declared in a block (i.e. { …}) is local to that block and can be used only within it and other blocks contained  under it. The names of the formal arguments are treated as if they were declared in the outermost block of that junction.

Function Scope.

The variables declared in the outer most block of a function have function scope, they can be accessed only in function declares them. Also labels (goto) have function scope, means they cannot be used outside the function.

File Scope.

A name declared outside of all functions of a program has file scope. It can be used by all the blocks and functions written inside the file in which the name declaration appears.

class Scope.

A name of class member has class scope and is local to its class.
Note** More on this topic will be continued latter. 

1 comment: