"Joe" <jc**********@comcast.net> wrote in message
news:11**********************@c13g2000cwb.googlegr oups.com...
If I remove the "static" from the definition, how do I keep a running
total in a function everytime the function is called?
For example, I pass a file arg to a function. The function opens the
file and parses each record. I want to keep a running total of all the
records parsed no matter how many times the function is called.
// test.h (#include this file in any module where you
// need to refer to 'total' or 'func()'
extern int total;
void func(int);
// test.cpp
int total(0); /* initializer of zero not required, but it's my
preferred style to initialize everything */
void func(int i)
{
total += i;
}
// main.cpp
#include <iostream>
#include "test.h"
int main()
{
func(42);
func(99);
std::cout << "total is: " << total << '\n'; // prints 141
return 0;
}
But I'd try to eliminate the need for a global if at all
possible. However I cannot advise you about how to do
that without knowing more about what your code needs to
do, and your overall design.
-Mike