Scope and Lifetime of Variables in C++

Scope and Lifetime of Variables in C++

In this article we examine the Scope and Lifetime of variables in C++. Understanding scope and lifetime is important to programmers because data integrity can be adversely impacted if this technology is not properly applied.

Definition of Scope and Lifetime

The Scope of a particular variable is the range within a program's source code in which that variable is recognized by the compiler. When scope rules are violated, errors will be generated during the compilation step. Technically these errors fall in the syntax category but conceptually they result from improper awareness of how scope rules are applied.

The Lifetime of a particular variable is the range within an executing program in which that variable is instantiated and retains its' value. When lifetime rules are violated, no compiler errors result, rather the program will demonstrate logic errors. Logic errors are typically much more difficult to isolate than compiler errors.

Local Variables vs Global Variables

Variables are categorized as either local or global solely based on there they are declared: inside a block out outside all blocks. A block is any code fragment enclosed in an left curly brace, {, and a right curly brace, }. Local variables are declared in a block. Global variables are declared outside of all blocks.

A local variable is limited in scope to all the code below the declaration until the end of the enclosing block. The variable is also visible to any other blocks that are enclosed in the original block.

A global variable is not limited in scope. This type of variable is visible to every module in the project. A commonly bemoaned shortcoming of C++ is the exposure created by using global variables. This situation is usually avoided by prohibiting the use of global variables and instead passing information between modules in the form of function/method parameters.

Static Local Variables

A variant of the 'normal' local variable is the static local. By prepending the keyword static to the variable declaration, a programmer can alter the lifetime of the variable. This keyword causes the compiler to preserve the value of the variable even when it goes out of scope; the lifetime becomes the entire execution of the program.When program execution reenters the blockn in which the variable is declared, the variable still has the value it had when execution last left that block.

Static Global Variables

A variant of the 'normal' global variable is the static global. Static global variables are visiible to all methods/functions in the module where the variable is declared, but not visible to any other modules in the project. This strategy greatly reduces the opportnities for logic errors in larger programs. Some coding standards endorse static global variables while discouraging non-static global variables. By doing this a mechanism for sharing information within a module is still provided. As long as modules are kept small and manageable, this strategy may prove useful. The final decision is left to the reader.

Summary of Scope and Lifetime Rules in C++

Declaration
Scope
Lifetime
Global
All the modules in the project
The life of the program execution
Static global
Only the module where declared
The life of the program execution
Local
The block in which it's declared
As long as execution is inside the block
Static local
The block in which it's declared
The life of the program

Samples of global and local variables in a code fragment

int intDelta;		// Global variable
static int intGamma;	// Static global variable

void Hoosier()
{
//	These variables are declared inside the block
//	 that makes up the Hoosier() function/method
	int	intAlpha;	// Local variable
	static int intBeta;	// Static local variable


}

A Caveat Regarding the Static Keyword

For better or worse, we are left with 2 different applications of the keyword static. As you study this tutorial, bear in mind that the keyword static applied to a local variable changes the lifetime of that variable. On the other hand, applying the keyword static to a global variable changes the scope of that variable.

Conclusion

A thorough understanding of Scope and Lifetime of variables in C++ is necessary to write robust and maintainable programs in C++ and also in C.

More by this Author


Comments 7 comments

Self 6 years ago

This rocks. An excellent overview of the static keyword. Well done!


Light 5 years ago

I am really not into posting comments and stuff ... Too lazy for that .. !! But this is an exception ...

Awwwwwwwwweeeeesome explanation .. Nothing can beat this one ... Too good ... !!! Great job !!

PS : Thanks a loooooooot ....... :)


student 5 years ago

good one..


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

@student : Thanks!


PARTH 5 years ago

Thnks!!!!!!!!!!!!!!!!!!!!


benny 4 years ago

kasanu ata?.


nicomp profile image

nicomp 2 years ago from Ohio, USA Author

This content has been stolen and republished at

https://sites.google.com/site/whirlingdervishescpl... .

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working