C++ Static variable Question

Introduction

Write a program that checks how many times a function was called from the main program.

To do this, we will use a static variable inside a function which will be incremented each time the function is called in main():

You can use the following code structure.

#include <iostream> 

int main() 
{ 
    //your code here
} 


#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(); 
    } 
} 



PreviousNext

Related