ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

Scope and Lifetime of Variables in C++

Updated on March 15, 2010

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.

Comments

    0 of 8192 characters used
    Post Comment

    • nicomp profile image
      Author

      nicomp really 3 years ago from Ohio, USA

      This content has been stolen and republished at

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

    • profile image

      benny 6 years ago

      kasanu ata?.

    • profile image

      PARTH 6 years ago

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

    • nicomp profile image
      Author

      nicomp really 6 years ago from Ohio, USA

      @student : Thanks!

    • profile image

      student 6 years ago

      good one..

    • profile image

      Light 6 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 ....... :)

    • profile image

      Self 8 years ago

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

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)