Since C++ 17 one can write an if
block that will get executed exactly once like this:
#include
In C++17 you can write
if (static int i; i == 0 && (i = 1)){
in order to avoid playing around with i
in the loop body. i
starts with 0 (guaranteed by the standard), and the expression after the ;
sets i
to 1
the first time it is evaluated.
Note that in C++11 you could achieve the same with a lambda function
if ([]{static int i; return i == 0 && (i = 1);}()){
which also carries a slight advantage in that i
is not leaked into the loop body.