How to make sure a function is only called once

前端 未结 5 1761
半阙折子戏
半阙折子戏 2021-01-31 17:56

Suppose I have a function named caller, which will call a function named callee:

void caller()
{
    callee();
}  

Now caller might be called m

5条回答
  •  悲哀的现实
    2021-01-31 18:34

    You could hide the function through a function pointer.

    static void real_function()
    {
      //do stuff
    
      function = noop_function;
    }
    
    
    static void noop_function()
    {
    
    }
    
    int (*function)(void) = real_function;
    

    Callers just call the function which will do the work the first time, and do nothing on any subsequent calls.

提交回复
热议问题