struct test{
int num;
};
int main(){
struct test t = {1234};
int n = *((int*)&t); // n = 1234
return 0;
}
Is the above snippet legal and causes no undefined behavior? I have seen this similar code snippet in production.
Edit: Please forgive the C style cast being used here.
The structure
is a standard layout structure. It is guaranteed that its data member
num
is at zero offset in the structuretest
.Standard layout structures are useful for communicating with code written in other programming languages as for example in C.
In C the address of an object of a structure type is equal to the address of its first data member.
From the C Standard (6.7.2.1 Structure and union specifiers)
So this code snippet
is valid and well-formed.
Instead of the C casting it is better to use the C++ casting
reinterpret_cast
.As @HolyBlackCat pointed to in his comment (For example the C++ 20 Standard, 6.8.3 Compound types)