1 / 7

Understanding Static Variables in C++ Functions: Scope and Lifetime

This article explores the concept of static variables in C++ functions, detailing their scope and lifecycle. Unlike normal local variables that are deallocated upon function termination, static variables retain their values between function calls. We'll discuss the rules governing static variable declarations and initialization, and examine practical examples, such as using a static variable to count function calls and track the largest value passed to a function. You'll also learn how to generate pseudo-random numbers using static variables for seed retention.

rafael-may
Télécharger la présentation

Understanding Static Variables in C++ Functions: Scope and Lifetime

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Static Variables

  2. Function Scope void f( ){    static <variable_type> <variable_name>    etc} “Normal” local variables go out of scope and are deallocated when a function terminates. Static variables remain and retain their value.

  3. Rules for Static Variables A static variable declaration is only executed once, the first time the function is executed. A static variable is initialized only once (since this is part of the declaration process) and will be initialized to 0 unless the programmer designates otherwise. Subsequent invocations of the function in which a static variable resides will retain the last value of that variable.

  4. void my_function ( ) {    static short count = 1;cout << "this function has been called " << count << (count == 1 ? "time" : "times");    count++; return;} int main() { for (inti = 0; i < 5; i++) my_function(); return 0; }

  5. void is_it_larger (const float val){    static float largest = val;    if (largest < val) // new val is larger         largest = val;cout << "The largest value sent to this function " << “so far is " << largest << endl;    return;} int main() { for (inti = 0; i < 7; i++) is_it_larger(i); return 0; }

  6. #include <ctime> // access to time clock long my_rand(){    static long seed = time(NULL);    seed = (104729 + seed * 7919) % 15485863;    return abs(seed);} int main() { for (inti = 5; i > 0; i--) cout<<my_rand()<<endl; return 0; }

  7. End of Session

More Related