I have an API with an open structure A and an internal structure B and should be able to convert structure B to structure A. Is the following code legal and well-defined behavior in C99 (and VS 2010 / C89) and C ++ 03 / C ++ eleven? If so, explain what makes it clear. If this is not the case, then what is the most efficient and cross-platform tool for converting between two structures?
struct A { uint32_t x; uint32_t y; uint32_t z; }; struct B { uint32_t x; uint32_t y; uint32_t z; uint64_t c; }; union U { struct A a; struct B b; }; int main(int argc, char* argv[]) { U u; ubx = 1; uby = 2; ubz = 3; ubc = 64; DoSomething(uax, uay, uaz); return 0; }
UPDATE
I simplified the example and wrote two different applications. One is based on memcpy, and the other is a union.
Union:
struct A { int x; int y; int z; }; struct B { int x; int y; int z; long c; }; union U { struct A a; struct B b; }; int main(int argc, char* argv[]) { U u; ubx = 1; uby = 2; ubz = 3; ubc = 64; const A* a = &u.a; return 0; }
Tetr:
Profiled assembly [DEBUG] (Xcode 6.4, default C ++ compiler):
Here is the corresponding build difference for debug mode. When I profiled release builds, there were no differences in the build.
Union:
movq %rcx, -48(%rbp)
Tetr:
movq -40(%rbp), %rsi movq %rsi, -56(%rbp) movl -32(%rbp), %edi movl %edi, -48(%rbp)
Reservation:
The merge-based sample code triggers a warning that the variable 'a' is not used. Since the profiled assembly is being debugged, I don't know if there are any consequences.
c ++ c c99 c89 unions
Coder Jul 22 '15 at 3:36 2015-07-22 03:36
source share