Why the output of this program is 4
?
#include
int main()
{
short A[] = {1, 2, 3, 4, 5, 6};
std::cout << *(short*)((c
The program has undefined behaviour due to casting an incorrectly aligned pointer to (short*)
. This breaks the rules in 6.3.2.3 p6 in C11, which is nothing to do with strict aliasing as claimed in other answers:
A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined.
In [expr.static.cast] p13 C++ says that converting the unaligned char*
to short*
gives an unspecified pointer value, which might be an invalid pointer, which can't be dereferenced.
The correct way to inspect the bytes is through the char*
not by casting back to short*
and pretending there is a short
at an address where a short
cannot live.