© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
S. DmitrovićModern C++ for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-9274-7_30

30. Exercises

Slobodan Dmitrović1  
(1)
Belgrade, Serbia
 

Static Variable

Write a program that checks how many times a function was called from the main program. We will use a local static variable inside a function, and we will increment this variable each time the function is called in main():
#include <iostream>
void myfunction()
{
    static int counter = 0;
    counter++;
    std::cout << "The function is called " << counter << " time(s)." << '\n';
}
int main()
{
    myfunction();
    myfunction();
    for (int i = 0; i < 5; i++)
    {
        myfunction();
    }
}
Output:
The function ...

Get Modern C++ for Absolute Beginners: A Friendly Introduction to the C++ Programming Language and C++11 to C++23 Standards now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.