Skip to content

Instantly share code, notes, and snippets.

@qrealka
Created June 26, 2019 09:48
Show Gist options
  • Save qrealka/e7340faa95b7053d339c0701625e22de to your computer and use it in GitHub Desktop.
Save qrealka/e7340faa95b7053d339c0701625e22de to your computer and use it in GitHub Desktop.
do once for IF
if (static bool do_once = true; std::exchange(do_once, false)) {
}
if (static bool do_once; !std::exchange(do_once, false)) {
}
struct Once {
bool b = true;
explicit operator bool() { return std::exchange(b, false); }
};
if (static Once _; _) {
}
// gcc, clang, icc only; use [[unlikely]] in C++20 instead
#define unlikely(x) __builtin_expect(!!(x), 0)
struct Once {
bool b = false;
explicit operator bool()
{
if (unlikely(not b)) {
b = true;
return true;
}
return false;
}
};
// C++17
if (static int i; i == 0 && (i = 1)){
}
// C++11
if ([]{static int i; return i == 0 && (i = 1);}()){
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment