0

If I desire to run a piece of code in a function, only from the second invocation of the function onwards,

Questions:

  1. Is there something wrong to do that?

  2. How can I possibly achieve this ? Is using a static variable to do this a good idea ?

nitin_cherian
  • 6,405
  • 21
  • 76
  • 127

3 Answers3

1
  1. Multi-threading will be a problem. To prevent this, if required, you'll probably need something like a mutex.

  2. Like this:

    void someFunction()
    {
       static bool firstRun = true;
       if (!firstRun)
       {
          // code to execute from the second time onwards
       }
       else
       {
          firstRun = false;
       }
       // other code
    }
    
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
1

There's two answers to this question, depending on whether you have to deal with multi-threaded serialization or not.

No threading:

void doSomething() {
    static bool firstTime = true;
    if (firstTime) {
       // do code specific to first pass
       firstTime = false;
    } else {
       // do code specific to 2nd+ pass
    }
    // do any code that is common
}

With threading: I'll write the generic boilerplate, but this code is system specific (requiring some variant of an atomic compareAndSet).

void doSomethingThreadSafe() {
    static volatile atomic<int> passState = 0;

    do {
        if ( passState == 2 ) {
            //perform pass 2+ code
            break;
        } else
        if ( passState.compareAndSet(0,1) ) { // if passState==0 set passState=1 return true else return false
            //perform pass 1 initialization code
            passState = 2;
            break;
        } else {
            //loser in setup collision, delay (wait for init code to finish) then retry
            sleep(1);
        }
    } while(1);

    //perform code common to all passes
}
Speed8ump
  • 1,307
  • 10
  • 25
-1

Add a global counter. eg:-

static int counter = 0;

public void testFunc(){

    if(counter==1){

       ........
       <Execute the functionality>
       ........

     }
    counter++;

}
Arun
  • 3,701
  • 5
  • 32
  • 43
  • This is not the only way, plus it leaves the counter out there for others to tamper with. The counter could be a `static` variable inside the function instead. Oh, and the question is tagged C++. – juanchopanza Sep 05 '13 at 13:54
  • then do it the c++ way :) – Arun Sep 05 '13 at 13:55
  • 2
    The is wrong in so many ways: 1) public voud? 2) doesn't deal with the multi-threaded question, 3) executes only on the second call, which wasn't the OP's request, 4) the counter will eventually roll over, 5) why initialize counter at 1 rather than 0? initialized at 1 it's hard to say what it's counting. 6) polluting the global namespace with names like 'counter' is a bad idea. – Speed8ump Sep 05 '13 at 14:19