The following code has an interesting form of undefined behavior:
#define STR_START "
#define STR_END "
int puts(const char *);
int main() {
puts(STR_START hello world STR_END);
The following code has an interesting form of undefined behavior:
#define STR_START "
#define STR_END "
int puts(const char *);
int main() {
puts(STR_START hello world STR_END);
This Is Just to Say
I have translated
the program
that was in
the translation units
and which
you were probably
expecting
What is strict aliasing? First we will describe what is aliasing and then we can learn what being strict about it means.
In C and C++ aliasing has to do with what expression types we are allowed to access stored values through. In both C and C++ the standard specifies which expression types are allowed to alias which types. The compiler and optimizer are allowed to assume we follow the aliasing rules strictly, hence the term strict aliasing rule. If we attempt to access a value using a type not allowed it is classified as undefined behavior(UB). Once we have undefined behavior all bets are off, the results of our program are no longer reliable.
Unfortunately with strict aliasing violations, we will often obtain the results we expect, leaving the possibility the a future version of a compiler with a new optimization will break code we th
In C++20 we will hopefully get bit_cast see the proposal and reference implementation. This utility should give us a simple and safe way to type pun.
The one issue I ran into with this utility is that is requires the size of the To and From type to be the same, as well as checking that To and From types are trivially copyable. The static_assert version of the check is as follows:
# define BIT_CAST_STATIC_ASSERTS(TO, FROM) do { \
static_assert(sizeof(TO) == sizeof(FROM)); \
static_assert(std::is_trivially_copyable<TO>::value); \
static_assert(std::is_trivially_copyable<FROM>::value); \
} while (false)