Is it safe to do type punning on char
types?
int *a = new int[3];
for(b = 0;b <= 2;b++){
a[b] = b;
}
char *ptr = (char*)&a;
I heard someone that type punning is only allowed for char
types without undefined behavior. Is this correct?
Casting a pointer to a valid object of any type to a character type and then accessing the pointer is valid in both C and C++. Normal restrictions still apply, so no trying to modify the char
referenced by the pointer if the original object was defined as const
, etc.
From the C Standard:
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
...
ā a character type.
From the C++ Standard:
If a program attempts to access (3.1) the stored value of an object through a glvalue whose type is not similar (7.3.6) to one of the following types the behavior is undefined:
...
ā a
char
,unsigned char
, orstd::byte
type.