How to execute a piece of code only once?

后端 未结 8 789
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 04:35

I have an application which has several functions in it. Each function can be called many times based on user input. However I need to execute a small segment of the code wi

相关标签:
8条回答
  • 2020-12-01 05:20

    could you do this

    have a function that return a bool or some datatype called init

    I made it happen this way, you need static bool to make it happens

    bool init()
    {
      cout << "Once " <<endl;
      return true||false;// value isn't matter
    }
    
    void functionCall()
    {
        static bool somebool = init(); // this line get executed once
        cout << "process " <<endl;
    }
    
    int main(int argc, char *argv[])
    {
        functionCall();
        functionCall();
        functionCall();
    
        return EXIT_SUCCESS;
    }
    

    for C

    #include <stdio.h>
    
    void init()
    {
        printf("init\n");
    }
    
    void process()
    {
        static int someint = 0;
        if(someint == 0)
        {
            someint = 1;
            init();
        }
        printf("process\n");
    }
    
    
    int main()
    {
        process();
        process();
        process();
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-01 05:22
    do { 
         //execute code once
    } while (false)
    
    0 讨论(0)
提交回复
热议问题