I recently was surprised to learn that the C and C++ language standards have a "strict aliasing" rule. In essence, the rule prohibits variables of differing types from referencing the same memory location.
As an example:
char buffer[4] = { 0x55, 0x66, 0x77, 0x88 };
int32 *p = (int32*)&buffer[0]; // illegal because buffer[0] and *p are different types
Most of the professional C++ developers I interact with are not familiar with this rule. Based on my research, it seems to affect mostly GCC/G++/CLANG users. Does Visual C++ support enabling/disabling this rule? If so, how does one do so?
Thank you
One of the lesser-known secrets of the C programming language is the so-called “strict aliasing rule”. This is a shame, because failing to adhere to it takes you (along with your code) straight into the realm of undefined behavior.
This is done because they referred to the same memory location. Strict Aliasing: GCC compiler makes an assumption that pointers of different types will never point to the same memory location i.e., alias of each other. Strict aliasing rule helps the compiler to optimize the code.
Visual Studio Code is a lightweight, cross-platform development environment that runs on Windows, Mac, and Linux systems. The Microsoft C/C++ for Visual Studio Code extension supports IntelliSense, debugging, code formatting, auto-completion. Visual Studio for Mac doesn't support Microsoft C++, but does support .
Two seemingly different pointers may point to storage locations in the same array (aliasing). As a result, data dependencies can arise when performing loop-based computations using pointers, as the pointers may potentially point to overlapping regions in memory.
"Strict aliasing" is a C++ rule restricting programs, not compilers. Since violating the rule is Undefined Behavior, no diagnostic required a compiler doesn't need to support it in any way.
That said, Microsoft is a bit less aggressive in applying optimizations. Only last week have they announced their new optimizer assumes no signed overflow, something that GCC has assumed for a few years already. Strict aliasing is going to break a few Windows headers, so those need fixing first. (A few types act as if they contain union
s, but they're not formally defined as such)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With