Callcount

Call count

This program demonstrates the use of static variables inside a function. The program declares a static variable inside a function and returns its address. In the main function the address is printed along with the value it points to.

Think about why static is required for the code to be valid, and what would happen if callCount wasn't static.

#include <iostream>

// Function that returns the address of a static variable
int* getCallCount() {
    static int callCount = 0; // Static variable to count function calls
    callCount++;
    return &callCount;
}

int main() {
    // Call the function multiple times
    getCallCount();
    getCallCount();
    getCallCount();

    // Print the address and value of the static variable
    int* countAddress = getCallCount();
    std::cout << "Address of callCount: " << countAddress << std::endl;
    std::cout << "Value of callCount: " << *countAddress << std::endl;

    return 0;
}

Answer

A non-static local variable would be destroyed when the function returns, making its address invalid outside the function scope. Declaring the variable as static ensures that the variable retains its value between calls, and that the address remains valid throughout the programs execution.

Questions