Hello World!
There are a lot of posts and articles on strict aliasing in C++ but my intention in this post is to make a fast and simple explanation on the strict aliasing. I'm adding a link to the very long post by Mike Anton on this topic at the end of my post. So let's cut the chase.
If we compile the code below without optimizations or with optimizations lower than -O2,
it will printout 196609 why? we are just swaping the first 16 bits with the second
(when casting from int to short we have (3 + (1 * 2^16)) after swapping we will have (1 + (3 * 2^16)) ).
What is going to happen when we compile this with -O2 or -O3?
gcc will turn on strict aliasing which does not allow casting our 32bit u_int to 16bit u_short.
For compiler our p pointer of type WORD * cannot point to the val of type DWORD.
Since it's not allowed it will just replace the code with returning the val.
And viola, for -O2 or -O3 the code will printout 65539.
A very good post on strict aliasing by Mike Acton.