Since C++ 17 one can write an if block that will get executed exactly once like this:
#include
You could wrap the one-time action in the constructor of a static object that you instantiate in place of the conditional.
Example:
#include
#include
struct do_once {
do_once(std::function fun) {
fun();
}
};
int main()
{
for (int i = 0; i < 3; ++i) {
static do_once action([](){ std::cout << "once\n"; });
std::cout << "Hello World\n";
}
}
Or you may indeed stick with a macro, that may look something like this:
#include
#define DO_ONCE(exp) \
do { \
static bool used_before = false; \
if (used_before) break; \
used_before = true; \
{ exp; } \
} while(0)
int main()
{
for (int i = 0; i < 3; ++i) {
DO_ONCE(std::cout << "once\n");
std::cout << "Hello World\n";
}
}