Since C++ 17 one can write an if
block that will get executed exactly once like this:
#include
Based on @Bathsheba's great answer for this - just made it even simpler.
In C++ 17
, you can simply do:
if (static int i; !i++) {
cout << "Execute once";
}
(In previous versions, just declare int i
outside the block. Also works in C :) ).
In simple words: you declare i, which takes default value of zero (0
).
Zero is falsey, therefore we use exclamation mark (!
) operator to negate it.
We then take into account the increment property of the
operator, which first gets processed (assigned, etc) and then incremented.
Therefore, in this block, i will be initialized and have the value 0
only once, when block gets executed, and then the value will increase. We simply use the !
operator to negate it.