Skip to content

Instantly share code, notes, and snippets.

@ming4883
Created August 12, 2014 04:28
Show Gist options
  • Save ming4883/bf00404b6be646ecfafa to your computer and use it in GitHub Desktop.
Save ming4883/bf00404b6be646ecfafa to your computer and use it in GitHub Desktop.
Avoiding compiler optimization on a variable with minimum impact on performance
/*
Usage example:
int a = my_rand();
int b = my_rand();
int c = a + b;
doNotOptimizeAway (c);
*/
template<class T>
inline void doNotOptimizeAway (T&& x)
{
volatile const char* c = reinterpret_cast<const char*>(&x);
if (c != c)
{
// the following should never be invoked
putchar (*c);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment