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? (
#include <iostream>
using namespace std;
int c=0;
void globalVariable();
int localVariable();
int main(){
for(int i=0; i<10; i++){
globalVariable();
}
for(int j=0; j<5; j++){
localVariable();
}
int local = localVariable();
cout << "Using global variable count = " << c << endl;
cout << "Using local variable count = " << local << endl;
return 0;
}
void globalVariable(){
c++;
}
int localVariable(){
static int local = 0;
local++;
return local;
}
Local variable cannot be used because it has no global access.
Comments
Leave a comment