Counter
Create a function that simply returns how many times it has been called. Limit all variables to inside the function. Print the value returned by the function inside the main function to verify that it works.
Hint
The static keyword makes variables initalize only once.
Answer
#include <iostream>
// Function that returns how many times it has been called
int countFunctionCalls() {
static int callCount = 0; // Static variable to count function calls
callCount++; // Increment the count
return callCount; // Return the current count
}
int main() {
// Loop to call the function multiple times and print the result
for (int i = 0; i < 10; ++i) {
int result = countFunctionCalls();
std::cout << "Function called " << result << " times." << std::endl;
}
return 0;
}
The static keyword makes the callCount variable retain its value between function calls. It is initialized only once and keeps its value across multiple calls to the function. Each time countFunctionCalls is called, the callCount variable is incremented, and the function returns the current count.