Question

How do I have main() remember the value of a variable each time it is called?

i.e. if I run this program the first time I want mainCallCounter = 0, but when I is called again I want it to increase the counter

#include <iostream>   
using namespace std;

static int mainCallCounter = 0;

void outputMainCallCount()
{
   cout << "Main was called" << mainCallCounter << "times." << endl;

}

int main()
{

    outputMainCallCount();
    mainCallCounter++;

return 0;
Was it helpful?

Solution 3

All variables declared in C++ expire when the program ends. If you want to persistently remember how many times the program has been run, you will need to store that data in an external file and update it whenever you run the program.

For example:

#include <iostream>
#include <fstream>

int numTimesRun() {
    std::ifstream input("counter.txt"); // assuming it exists
    int numTimesRun;
    input >> numTimesRun;
    return numTimesRun;
}

void updateCounter() {
    int counter = numTimesRun();
    std::ofstream output("counter.txt");
    output << counter;
}

int main() {
    int timesRun = numTimesRun();
    updateCounter();

    /* ... */
}

Hope this helps!

OTHER TIPS

Main is the entry point for your program. Main is called once (normally) and, when it exits, your program is torn down and cleaned up.

Obviously this means a local variable will be insufficient. You need some sort of external storage which persists longer than your application, i.e., the file system.

You can't. Each run of a program is independent. You will need to save mainCallCounter somewhere and re-read it the next time the application launches. Writing it into a file is one option, another might be something like the Windows registry or Mac OS X defaults system, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top