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?
Using the global variable to store the count
#include<iostream>
using namespace std;
int n = 0 ;
int functionCalled(){
n++;
return n;
}
int main(){
int x = 0;
for(int i=0; i<10; i++){
x = functionCalled();
}
cout<<"I have been called "<<x<<" times";
}
Using a local static variable to store the count
#include<iostream>
using namespace std;
int functionCalled(){
static int n = 0 ;
n++;
return n;
}
int main(){
int x = 0;
for(int i=0; i<10; i++){
x = functionCalled();
}
cout<<"I have been called "<<x<<" times";
}
Local variables cannot be used because they cannot be accessed outside the function.
Comments
Leave a comment