Using a static function variable vs a class variable to store some state

Suppose I have a function:

void processElement() {
    doSomething(someArray[lastProcessedElement + 1]);
}

The fact is that whenever this function is called, I need to save the last element that I called doSomething. So, I have two options:

  • I can create a private class variable called lastProcessedElement and increment its value each time this function is called. This approach seems to be the most common. So the code could be something like this:

    class Foo {
        int lastProcessedElement = 0;     
    
        public:  
        void processElement() {
            doSomething(someArray[++lastProcessedElement]);
        }
    }
    
  • As a second option, I can create a static variable in the function and increment it every time:

    // Class is not important here, so the function is:
    void processElement() {
        static int lastProcessedElement = 0;
        doSomething(someArray[++lastProcessedElement]);
    }
    

The first solution adds a bit of complexity that I don't want. I like to keep things in place.

, , .

, ? multi-instance? ( , , )

+4
1

, - :

,

.

.

+5

All Articles