mardi 25 juin 2019

Most elegant way to write a one shot IF

Since C++ 17 one can write an If-block that will get executed exactly once like this:

#include <iostream>
int main() {
    for (unsigned i = 0; i < 10; ++i) {

        if (static bool do_once = true; do_once) { // enter only once
            std::cout << "hello one-shot" << std::endl;
            // possibly much more code
            do_once = false;
        }

    }
}

I know I might be overthinking this, 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 do_once = false at the end?

if (DO_ONCE) {
    // do stuff
}

I'm thinking a helper function do_once() containing the static bool do_once, but what if i wanted to use that same function in different places? Might this be the time and place for a #define? I hope not.

Aucun commentaire:

Enregistrer un commentaire