Write a function that, when you call it, displays a message telling how many times it has been called: “I have been called 3 times”, for instance. Write a main()program that calls this function at least 10 times. Try implementing this function in two different ways. First, use a global variable to store the count. Second, use a local static variable. Which is more appropriate? Why can’t you use a local variable.
Fix typo
#include <iostream>
using namespace std;
int funCalls=0;
void fun1() {
funCalls++;
cout << "I am fun1 and I have been called " << funCalls << " times" << endl;
}
void fun2() {
static int funCalls=0;
funCalls++;
cout << "I am fun2 and I have been called " << funCalls << " times" << endl;
}
int main() {
for (int i=0; i<10; i++)
fun1();
cout << endl;
for (int i=0; i<10; i++)
fun2();
}
// The second approach is more suitable as nobody can't change the value
// of the variable count.
// A local variable can't be used as it "forgot" its value everytime
// the functon is called.
Comments
Leave a comment