home page of dan zwell

C++ tricks

I release all code samples on this page to the public domain.

Evaluate once

It is simple to execute code just once in C or C++:

static warned = false; if (not warned) { warned = true; printf("Consider yourself warned.\n"); }

That works, but it feels tedious. Let's wrap it in a macro:

#define EVAL_ONCE \ static bool EVALUATED_ONCE = false; \ if (! EVALUATED_ONCE and !(EVALUATED_ONCE = true)) EVAL_ONCE { printf("Consider yourself warned.\n"); }

The above fails on two counts. First, it's not a single statement, so if someone puts EVAL_ONCE{ ... } in an if statement without braces, it will fail to compile. Second, this macro pollutes the namespace with its tracking variable, and so cannot be used twice in the same scope.

We can fix these issues by using a loop to declare the static variable, and the macro works as desired:

#define EVAL_ONCE \ for (static int EVALUATED = 0; EVALUATED == 0; ++EVALUATED)