How to execute a piece of code only once?











up vote
15
down vote

favorite
5












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 within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.










share|improve this question


















  • 11




    Can't you just put it at the beginning (or whatever it needs to be) in the main? Or before the main loop of the program?
    – Kiril Kirov
    Dec 7 '11 at 9:01















up vote
15
down vote

favorite
5












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 within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.










share|improve this question


















  • 11




    Can't you just put it at the beginning (or whatever it needs to be) in the main? Or before the main loop of the program?
    – Kiril Kirov
    Dec 7 '11 at 9:01













up vote
15
down vote

favorite
5









up vote
15
down vote

favorite
5






5





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 within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.










share|improve this question













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 within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.







c++ static global-variables






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 7 '11 at 8:59









Darzen

5293825




5293825








  • 11




    Can't you just put it at the beginning (or whatever it needs to be) in the main? Or before the main loop of the program?
    – Kiril Kirov
    Dec 7 '11 at 9:01














  • 11




    Can't you just put it at the beginning (or whatever it needs to be) in the main? Or before the main loop of the program?
    – Kiril Kirov
    Dec 7 '11 at 9:01








11




11




Can't you just put it at the beginning (or whatever it needs to be) in the main? Or before the main loop of the program?
– Kiril Kirov
Dec 7 '11 at 9:01




Can't you just put it at the beginning (or whatever it needs to be) in the main? Or before the main loop of the program?
– Kiril Kirov
Dec 7 '11 at 9:01












6 Answers
6






active

oldest

votes

















up vote
20
down vote



accepted










Use global static objects with constructors (which are called before main)? Or just inside a routine



static bool initialized;
if (!initialized) {
initialized = true;
// do the initialization part
}


There are very few cases when this is not fast enough!





addenda



In multithreaded context this might not be enough:



You may also be interested in pthread_once or constructor function __attribute__ of GCC.



With C++11, you may want std::call_once.



You may want to use <atomic> and perhaps declare static volatile std::atomic_bool initialized; (but you need to be careful) if your function can be called from several threads.



But these might not be available on your system; they are available on Linux!






share|improve this answer



















  • 1




    That was my thought too, but then reading @KirilKirov's comment I had to bang my head against some stonework. Cheers,
    – Cheers and hth. - Alf
    Dec 7 '11 at 9:05










  • Hey thanks Basile :)
    – Darzen
    Dec 7 '11 at 10:59






  • 1




    This won't work as is in a multithreaded setting but should good for most use cases
    – Kat
    Oct 17 '13 at 18:27










  • Make sure to initialize that bool to false! static bool initialized(false); otherwise you never know what'll be in memory once allocated.
    – thayne
    Jun 5 '17 at 20:10










  • AFAIK, a static variable is initialized to all-zero bits, which is false for a bool
    – Basile Starynkevitch
    Jun 6 '17 at 0:17


















up vote
17
down vote













Compact version using lambda function:



void foo()
{
static bool once = (){
cout << "once" << endl;
return true;
} ();
cout << "foo" << endl;
}


Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.






share|improve this answer























  • Excellent, I was thinking that the compiler already does that when initializing a static and thus we should be able to benefit from that and here is the right answer (instead of using a flag or run_once())
    – Alexis Wilke
    Oct 11 '16 at 4:29










  • @Bediver if you store that lambda inside an auto variable instead of executing it immediately, it will be able to be called more than once. Or is that UB?
    – Nik-Lz
    Oct 3 at 18:21




















up vote
17
down vote













Using C++11 -- use the std::call_once



#include <mutex>

std::once_flag onceFlag;

{
....
std::call_once ( onceFlag, [ ]{ /* my code body here runs only once */ } );
....
}





share|improve this answer























  • I didn't know about this API, thanks. A couple of things: Firstly make sure onceFlag has global scope. It can't have thread or function scope. Secondly, I don't see a way to easily compact this down to a single expression. (Not a huge deal compared to having a clear, standard API.)
    – John McFarlane
    Jun 27 '14 at 16:16






  • 1




    I am using this to great affect, the only thing I would do to improve upon it is if you declare your once_flag inside the function as a static, it will only be initialized once and your code inside call_once will only run once, but you can keep all the code in the same scope.
    – Andrew97p
    Jan 12 '16 at 23:43


















up vote
15
down vote













You can use local static variable:



void foo()
{
static bool wasExecuted = false;
if (wasExecuted)
return;
wasExecuted = true;

...
}





share|improve this answer




























    up vote
    6
    down vote













    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;
    }





    share|improve this answer























    • Is it executed once because "static will be initialised only once" ??
      – Makesh
      Apr 27 '16 at 12:25




















    up vote
    3
    down vote













    Additionally to @Basile's answer, you can use a lambda to encapsulate the static variable as follows:



    if ( {
    static bool is_first_time = true;
    auto was_first_time = is_first_time;
    is_first_time = false;
    return was_first_time; } ())
    {
    // do the initialization part
    }


    This makes it easy to convert into a general-purpose macro:



    #define FIRST_TIME_HERE ( { 
    static bool is_first_time = true;
    auto was_first_time = is_first_time;
    is_first_time = false;
    return was_first_time; } ())


    Which can be placed anywhere you want call-by-need:



    if (FIRST_TIME_HERE) {
    // do the initialization part
    }


    And for good measure, atomics shorten the expression and make it thread-safe:



    #include <atomic>
    #define FIRST_TIME_HERE ( {
    static std::atomic<bool> first_time(true);
    return first_time.exchange(false); } ())





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8412630%2fhow-to-execute-a-piece-of-code-only-once%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      20
      down vote



      accepted










      Use global static objects with constructors (which are called before main)? Or just inside a routine



      static bool initialized;
      if (!initialized) {
      initialized = true;
      // do the initialization part
      }


      There are very few cases when this is not fast enough!





      addenda



      In multithreaded context this might not be enough:



      You may also be interested in pthread_once or constructor function __attribute__ of GCC.



      With C++11, you may want std::call_once.



      You may want to use <atomic> and perhaps declare static volatile std::atomic_bool initialized; (but you need to be careful) if your function can be called from several threads.



      But these might not be available on your system; they are available on Linux!






      share|improve this answer



















      • 1




        That was my thought too, but then reading @KirilKirov's comment I had to bang my head against some stonework. Cheers,
        – Cheers and hth. - Alf
        Dec 7 '11 at 9:05










      • Hey thanks Basile :)
        – Darzen
        Dec 7 '11 at 10:59






      • 1




        This won't work as is in a multithreaded setting but should good for most use cases
        – Kat
        Oct 17 '13 at 18:27










      • Make sure to initialize that bool to false! static bool initialized(false); otherwise you never know what'll be in memory once allocated.
        – thayne
        Jun 5 '17 at 20:10










      • AFAIK, a static variable is initialized to all-zero bits, which is false for a bool
        – Basile Starynkevitch
        Jun 6 '17 at 0:17















      up vote
      20
      down vote



      accepted










      Use global static objects with constructors (which are called before main)? Or just inside a routine



      static bool initialized;
      if (!initialized) {
      initialized = true;
      // do the initialization part
      }


      There are very few cases when this is not fast enough!





      addenda



      In multithreaded context this might not be enough:



      You may also be interested in pthread_once or constructor function __attribute__ of GCC.



      With C++11, you may want std::call_once.



      You may want to use <atomic> and perhaps declare static volatile std::atomic_bool initialized; (but you need to be careful) if your function can be called from several threads.



      But these might not be available on your system; they are available on Linux!






      share|improve this answer



















      • 1




        That was my thought too, but then reading @KirilKirov's comment I had to bang my head against some stonework. Cheers,
        – Cheers and hth. - Alf
        Dec 7 '11 at 9:05










      • Hey thanks Basile :)
        – Darzen
        Dec 7 '11 at 10:59






      • 1




        This won't work as is in a multithreaded setting but should good for most use cases
        – Kat
        Oct 17 '13 at 18:27










      • Make sure to initialize that bool to false! static bool initialized(false); otherwise you never know what'll be in memory once allocated.
        – thayne
        Jun 5 '17 at 20:10










      • AFAIK, a static variable is initialized to all-zero bits, which is false for a bool
        – Basile Starynkevitch
        Jun 6 '17 at 0:17













      up vote
      20
      down vote



      accepted







      up vote
      20
      down vote



      accepted






      Use global static objects with constructors (which are called before main)? Or just inside a routine



      static bool initialized;
      if (!initialized) {
      initialized = true;
      // do the initialization part
      }


      There are very few cases when this is not fast enough!





      addenda



      In multithreaded context this might not be enough:



      You may also be interested in pthread_once or constructor function __attribute__ of GCC.



      With C++11, you may want std::call_once.



      You may want to use <atomic> and perhaps declare static volatile std::atomic_bool initialized; (but you need to be careful) if your function can be called from several threads.



      But these might not be available on your system; they are available on Linux!






      share|improve this answer














      Use global static objects with constructors (which are called before main)? Or just inside a routine



      static bool initialized;
      if (!initialized) {
      initialized = true;
      // do the initialization part
      }


      There are very few cases when this is not fast enough!





      addenda



      In multithreaded context this might not be enough:



      You may also be interested in pthread_once or constructor function __attribute__ of GCC.



      With C++11, you may want std::call_once.



      You may want to use <atomic> and perhaps declare static volatile std::atomic_bool initialized; (but you need to be careful) if your function can be called from several threads.



      But these might not be available on your system; they are available on Linux!







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jan 11 at 13:12

























      answered Dec 7 '11 at 9:02









      Basile Starynkevitch

      174k13163357




      174k13163357








      • 1




        That was my thought too, but then reading @KirilKirov's comment I had to bang my head against some stonework. Cheers,
        – Cheers and hth. - Alf
        Dec 7 '11 at 9:05










      • Hey thanks Basile :)
        – Darzen
        Dec 7 '11 at 10:59






      • 1




        This won't work as is in a multithreaded setting but should good for most use cases
        – Kat
        Oct 17 '13 at 18:27










      • Make sure to initialize that bool to false! static bool initialized(false); otherwise you never know what'll be in memory once allocated.
        – thayne
        Jun 5 '17 at 20:10










      • AFAIK, a static variable is initialized to all-zero bits, which is false for a bool
        – Basile Starynkevitch
        Jun 6 '17 at 0:17














      • 1




        That was my thought too, but then reading @KirilKirov's comment I had to bang my head against some stonework. Cheers,
        – Cheers and hth. - Alf
        Dec 7 '11 at 9:05










      • Hey thanks Basile :)
        – Darzen
        Dec 7 '11 at 10:59






      • 1




        This won't work as is in a multithreaded setting but should good for most use cases
        – Kat
        Oct 17 '13 at 18:27










      • Make sure to initialize that bool to false! static bool initialized(false); otherwise you never know what'll be in memory once allocated.
        – thayne
        Jun 5 '17 at 20:10










      • AFAIK, a static variable is initialized to all-zero bits, which is false for a bool
        – Basile Starynkevitch
        Jun 6 '17 at 0:17








      1




      1




      That was my thought too, but then reading @KirilKirov's comment I had to bang my head against some stonework. Cheers,
      – Cheers and hth. - Alf
      Dec 7 '11 at 9:05




      That was my thought too, but then reading @KirilKirov's comment I had to bang my head against some stonework. Cheers,
      – Cheers and hth. - Alf
      Dec 7 '11 at 9:05












      Hey thanks Basile :)
      – Darzen
      Dec 7 '11 at 10:59




      Hey thanks Basile :)
      – Darzen
      Dec 7 '11 at 10:59




      1




      1




      This won't work as is in a multithreaded setting but should good for most use cases
      – Kat
      Oct 17 '13 at 18:27




      This won't work as is in a multithreaded setting but should good for most use cases
      – Kat
      Oct 17 '13 at 18:27












      Make sure to initialize that bool to false! static bool initialized(false); otherwise you never know what'll be in memory once allocated.
      – thayne
      Jun 5 '17 at 20:10




      Make sure to initialize that bool to false! static bool initialized(false); otherwise you never know what'll be in memory once allocated.
      – thayne
      Jun 5 '17 at 20:10












      AFAIK, a static variable is initialized to all-zero bits, which is false for a bool
      – Basile Starynkevitch
      Jun 6 '17 at 0:17




      AFAIK, a static variable is initialized to all-zero bits, which is false for a bool
      – Basile Starynkevitch
      Jun 6 '17 at 0:17












      up vote
      17
      down vote













      Compact version using lambda function:



      void foo()
      {
      static bool once = (){
      cout << "once" << endl;
      return true;
      } ();
      cout << "foo" << endl;
      }


      Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.






      share|improve this answer























      • Excellent, I was thinking that the compiler already does that when initializing a static and thus we should be able to benefit from that and here is the right answer (instead of using a flag or run_once())
        – Alexis Wilke
        Oct 11 '16 at 4:29










      • @Bediver if you store that lambda inside an auto variable instead of executing it immediately, it will be able to be called more than once. Or is that UB?
        – Nik-Lz
        Oct 3 at 18:21

















      up vote
      17
      down vote













      Compact version using lambda function:



      void foo()
      {
      static bool once = (){
      cout << "once" << endl;
      return true;
      } ();
      cout << "foo" << endl;
      }


      Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.






      share|improve this answer























      • Excellent, I was thinking that the compiler already does that when initializing a static and thus we should be able to benefit from that and here is the right answer (instead of using a flag or run_once())
        – Alexis Wilke
        Oct 11 '16 at 4:29










      • @Bediver if you store that lambda inside an auto variable instead of executing it immediately, it will be able to be called more than once. Or is that UB?
        – Nik-Lz
        Oct 3 at 18:21















      up vote
      17
      down vote










      up vote
      17
      down vote









      Compact version using lambda function:



      void foo()
      {
      static bool once = (){
      cout << "once" << endl;
      return true;
      } ();
      cout << "foo" << endl;
      }


      Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.






      share|improve this answer














      Compact version using lambda function:



      void foo()
      {
      static bool once = (){
      cout << "once" << endl;
      return true;
      } ();
      cout << "foo" << endl;
      }


      Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Oct 11 '16 at 4:27









      Alexis Wilke

      9,57623877




      9,57623877










      answered Apr 13 '16 at 11:16









      Bediver

      34426




      34426












      • Excellent, I was thinking that the compiler already does that when initializing a static and thus we should be able to benefit from that and here is the right answer (instead of using a flag or run_once())
        – Alexis Wilke
        Oct 11 '16 at 4:29










      • @Bediver if you store that lambda inside an auto variable instead of executing it immediately, it will be able to be called more than once. Or is that UB?
        – Nik-Lz
        Oct 3 at 18:21




















      • Excellent, I was thinking that the compiler already does that when initializing a static and thus we should be able to benefit from that and here is the right answer (instead of using a flag or run_once())
        – Alexis Wilke
        Oct 11 '16 at 4:29










      • @Bediver if you store that lambda inside an auto variable instead of executing it immediately, it will be able to be called more than once. Or is that UB?
        – Nik-Lz
        Oct 3 at 18:21


















      Excellent, I was thinking that the compiler already does that when initializing a static and thus we should be able to benefit from that and here is the right answer (instead of using a flag or run_once())
      – Alexis Wilke
      Oct 11 '16 at 4:29




      Excellent, I was thinking that the compiler already does that when initializing a static and thus we should be able to benefit from that and here is the right answer (instead of using a flag or run_once())
      – Alexis Wilke
      Oct 11 '16 at 4:29












      @Bediver if you store that lambda inside an auto variable instead of executing it immediately, it will be able to be called more than once. Or is that UB?
      – Nik-Lz
      Oct 3 at 18:21






      @Bediver if you store that lambda inside an auto variable instead of executing it immediately, it will be able to be called more than once. Or is that UB?
      – Nik-Lz
      Oct 3 at 18:21












      up vote
      17
      down vote













      Using C++11 -- use the std::call_once



      #include <mutex>

      std::once_flag onceFlag;

      {
      ....
      std::call_once ( onceFlag, [ ]{ /* my code body here runs only once */ } );
      ....
      }





      share|improve this answer























      • I didn't know about this API, thanks. A couple of things: Firstly make sure onceFlag has global scope. It can't have thread or function scope. Secondly, I don't see a way to easily compact this down to a single expression. (Not a huge deal compared to having a clear, standard API.)
        – John McFarlane
        Jun 27 '14 at 16:16






      • 1




        I am using this to great affect, the only thing I would do to improve upon it is if you declare your once_flag inside the function as a static, it will only be initialized once and your code inside call_once will only run once, but you can keep all the code in the same scope.
        – Andrew97p
        Jan 12 '16 at 23:43















      up vote
      17
      down vote













      Using C++11 -- use the std::call_once



      #include <mutex>

      std::once_flag onceFlag;

      {
      ....
      std::call_once ( onceFlag, [ ]{ /* my code body here runs only once */ } );
      ....
      }





      share|improve this answer























      • I didn't know about this API, thanks. A couple of things: Firstly make sure onceFlag has global scope. It can't have thread or function scope. Secondly, I don't see a way to easily compact this down to a single expression. (Not a huge deal compared to having a clear, standard API.)
        – John McFarlane
        Jun 27 '14 at 16:16






      • 1




        I am using this to great affect, the only thing I would do to improve upon it is if you declare your once_flag inside the function as a static, it will only be initialized once and your code inside call_once will only run once, but you can keep all the code in the same scope.
        – Andrew97p
        Jan 12 '16 at 23:43













      up vote
      17
      down vote










      up vote
      17
      down vote









      Using C++11 -- use the std::call_once



      #include <mutex>

      std::once_flag onceFlag;

      {
      ....
      std::call_once ( onceFlag, [ ]{ /* my code body here runs only once */ } );
      ....
      }





      share|improve this answer














      Using C++11 -- use the std::call_once



      #include <mutex>

      std::once_flag onceFlag;

      {
      ....
      std::call_once ( onceFlag, [ ]{ /* my code body here runs only once */ } );
      ....
      }






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jul 30 '17 at 22:31









      BeeOnRope

      24.4k873169




      24.4k873169










      answered Jun 21 '14 at 1:31









      Soren

      12k42858




      12k42858












      • I didn't know about this API, thanks. A couple of things: Firstly make sure onceFlag has global scope. It can't have thread or function scope. Secondly, I don't see a way to easily compact this down to a single expression. (Not a huge deal compared to having a clear, standard API.)
        – John McFarlane
        Jun 27 '14 at 16:16






      • 1




        I am using this to great affect, the only thing I would do to improve upon it is if you declare your once_flag inside the function as a static, it will only be initialized once and your code inside call_once will only run once, but you can keep all the code in the same scope.
        – Andrew97p
        Jan 12 '16 at 23:43


















      • I didn't know about this API, thanks. A couple of things: Firstly make sure onceFlag has global scope. It can't have thread or function scope. Secondly, I don't see a way to easily compact this down to a single expression. (Not a huge deal compared to having a clear, standard API.)
        – John McFarlane
        Jun 27 '14 at 16:16






      • 1




        I am using this to great affect, the only thing I would do to improve upon it is if you declare your once_flag inside the function as a static, it will only be initialized once and your code inside call_once will only run once, but you can keep all the code in the same scope.
        – Andrew97p
        Jan 12 '16 at 23:43
















      I didn't know about this API, thanks. A couple of things: Firstly make sure onceFlag has global scope. It can't have thread or function scope. Secondly, I don't see a way to easily compact this down to a single expression. (Not a huge deal compared to having a clear, standard API.)
      – John McFarlane
      Jun 27 '14 at 16:16




      I didn't know about this API, thanks. A couple of things: Firstly make sure onceFlag has global scope. It can't have thread or function scope. Secondly, I don't see a way to easily compact this down to a single expression. (Not a huge deal compared to having a clear, standard API.)
      – John McFarlane
      Jun 27 '14 at 16:16




      1




      1




      I am using this to great affect, the only thing I would do to improve upon it is if you declare your once_flag inside the function as a static, it will only be initialized once and your code inside call_once will only run once, but you can keep all the code in the same scope.
      – Andrew97p
      Jan 12 '16 at 23:43




      I am using this to great affect, the only thing I would do to improve upon it is if you declare your once_flag inside the function as a static, it will only be initialized once and your code inside call_once will only run once, but you can keep all the code in the same scope.
      – Andrew97p
      Jan 12 '16 at 23:43










      up vote
      15
      down vote













      You can use local static variable:



      void foo()
      {
      static bool wasExecuted = false;
      if (wasExecuted)
      return;
      wasExecuted = true;

      ...
      }





      share|improve this answer

























        up vote
        15
        down vote













        You can use local static variable:



        void foo()
        {
        static bool wasExecuted = false;
        if (wasExecuted)
        return;
        wasExecuted = true;

        ...
        }





        share|improve this answer























          up vote
          15
          down vote










          up vote
          15
          down vote









          You can use local static variable:



          void foo()
          {
          static bool wasExecuted = false;
          if (wasExecuted)
          return;
          wasExecuted = true;

          ...
          }





          share|improve this answer












          You can use local static variable:



          void foo()
          {
          static bool wasExecuted = false;
          if (wasExecuted)
          return;
          wasExecuted = true;

          ...
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 7 '11 at 9:02









          Abyx

          7,99233065




          7,99233065






















              up vote
              6
              down vote













              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;
              }





              share|improve this answer























              • Is it executed once because "static will be initialised only once" ??
                – Makesh
                Apr 27 '16 at 12:25

















              up vote
              6
              down vote













              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;
              }





              share|improve this answer























              • Is it executed once because "static will be initialised only once" ??
                – Makesh
                Apr 27 '16 at 12:25















              up vote
              6
              down vote










              up vote
              6
              down vote









              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;
              }





              share|improve this answer














              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;
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Oct 23 '13 at 15:02

























              answered Oct 17 '13 at 18:53









              aah134

              585921




              585921












              • Is it executed once because "static will be initialised only once" ??
                – Makesh
                Apr 27 '16 at 12:25




















              • Is it executed once because "static will be initialised only once" ??
                – Makesh
                Apr 27 '16 at 12:25


















              Is it executed once because "static will be initialised only once" ??
              – Makesh
              Apr 27 '16 at 12:25






              Is it executed once because "static will be initialised only once" ??
              – Makesh
              Apr 27 '16 at 12:25












              up vote
              3
              down vote













              Additionally to @Basile's answer, you can use a lambda to encapsulate the static variable as follows:



              if ( {
              static bool is_first_time = true;
              auto was_first_time = is_first_time;
              is_first_time = false;
              return was_first_time; } ())
              {
              // do the initialization part
              }


              This makes it easy to convert into a general-purpose macro:



              #define FIRST_TIME_HERE ( { 
              static bool is_first_time = true;
              auto was_first_time = is_first_time;
              is_first_time = false;
              return was_first_time; } ())


              Which can be placed anywhere you want call-by-need:



              if (FIRST_TIME_HERE) {
              // do the initialization part
              }


              And for good measure, atomics shorten the expression and make it thread-safe:



              #include <atomic>
              #define FIRST_TIME_HERE ( {
              static std::atomic<bool> first_time(true);
              return first_time.exchange(false); } ())





              share|improve this answer

























                up vote
                3
                down vote













                Additionally to @Basile's answer, you can use a lambda to encapsulate the static variable as follows:



                if ( {
                static bool is_first_time = true;
                auto was_first_time = is_first_time;
                is_first_time = false;
                return was_first_time; } ())
                {
                // do the initialization part
                }


                This makes it easy to convert into a general-purpose macro:



                #define FIRST_TIME_HERE ( { 
                static bool is_first_time = true;
                auto was_first_time = is_first_time;
                is_first_time = false;
                return was_first_time; } ())


                Which can be placed anywhere you want call-by-need:



                if (FIRST_TIME_HERE) {
                // do the initialization part
                }


                And for good measure, atomics shorten the expression and make it thread-safe:



                #include <atomic>
                #define FIRST_TIME_HERE ( {
                static std::atomic<bool> first_time(true);
                return first_time.exchange(false); } ())





                share|improve this answer























                  up vote
                  3
                  down vote










                  up vote
                  3
                  down vote









                  Additionally to @Basile's answer, you can use a lambda to encapsulate the static variable as follows:



                  if ( {
                  static bool is_first_time = true;
                  auto was_first_time = is_first_time;
                  is_first_time = false;
                  return was_first_time; } ())
                  {
                  // do the initialization part
                  }


                  This makes it easy to convert into a general-purpose macro:



                  #define FIRST_TIME_HERE ( { 
                  static bool is_first_time = true;
                  auto was_first_time = is_first_time;
                  is_first_time = false;
                  return was_first_time; } ())


                  Which can be placed anywhere you want call-by-need:



                  if (FIRST_TIME_HERE) {
                  // do the initialization part
                  }


                  And for good measure, atomics shorten the expression and make it thread-safe:



                  #include <atomic>
                  #define FIRST_TIME_HERE ( {
                  static std::atomic<bool> first_time(true);
                  return first_time.exchange(false); } ())





                  share|improve this answer












                  Additionally to @Basile's answer, you can use a lambda to encapsulate the static variable as follows:



                  if ( {
                  static bool is_first_time = true;
                  auto was_first_time = is_first_time;
                  is_first_time = false;
                  return was_first_time; } ())
                  {
                  // do the initialization part
                  }


                  This makes it easy to convert into a general-purpose macro:



                  #define FIRST_TIME_HERE ( { 
                  static bool is_first_time = true;
                  auto was_first_time = is_first_time;
                  is_first_time = false;
                  return was_first_time; } ())


                  Which can be placed anywhere you want call-by-need:



                  if (FIRST_TIME_HERE) {
                  // do the initialization part
                  }


                  And for good measure, atomics shorten the expression and make it thread-safe:



                  #include <atomic>
                  #define FIRST_TIME_HERE ( {
                  static std::atomic<bool> first_time(true);
                  return first_time.exchange(false); } ())






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 15 '14 at 0:21









                  John McFarlane

                  2,23921723




                  2,23921723






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8412630%2fhow-to-execute-a-piece-of-code-only-once%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Florida Star v. B. J. F.

                      Danny Elfman

                      Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues