title: Most elegant way to write a one-shot 'if'
body: <p>Since C++ 17 one can write an <code>if</code> block that will get executed exactly once like this:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;
  int main() {
      for (unsigned i = 0; i &lt; 10; ++i) {
  
          if (static bool do_once = true; do_once) { // Enter only once
              std::cout &lt;&lt; "hello one-shot" &lt;&lt; std::endl;
              // Possibly much more code
              do_once = false;
          }
  
      }
  }
  </code></pre>
  
  <p>I know I might be overthinking this, and there are other ways to solve this, but still - is it possible to write this somehow like this, so there is no need of the <code>do_once = false</code> at the end?</p>
  
  <pre><code>if (DO_ONCE) {
      // Do stuff
  }
  </code></pre>
  
  <p>I'm thinking a helper function, <code>do_once()</code>, containing the <code>static bool do_once</code>, but what if I wanted to use that same function in different places? Might this be the time and place for a <code>#define</code>? I hope not.</p>