-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunions_align.cpp
66 lines (57 loc) · 1.65 KB
/
unions_align.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*****************************************************************//**
* \file unions_align.cpp
* \brief contains notes and examples on unions
*
* Most important thing to remember:
* An union only allows 1 of its member attribute to exist
* The latter assigned value overwrites the former.
*
* \author Xuhua Huang
* \date June 2021
*********************************************************************/
#include <iostream>
struct Vector2D {
float x, y;
};
struct Vector4D {
union {
struct // anonymous struct
{
float x, y, z, w;
};
struct {
/**
* memory of x and y of type float is aligned with Vector2D v1
* memory of z and w of type float is aligned with Vector2D v2
*/
Vector2D v1, v2;
};
};
};
void printVector2D(const Vector2D& vector) {
std::cout << __func__ << "\n"
<< "Printing struct Vector2D, x: " << vector.x << ", y: " << vector.y << "\n";
return;
}
int main(void) {
/* Basic syntax
union
{
float a;
int b;
};
*/
Vector4D vector = {1.0f, 2.0f, 3.0f, 4.0f};
printVector2D(vector.v1); // retrieving member in the second anonymous struct
// 1.0 and 2.0
printVector2D(vector.v2);
// 3.0 and 4.0
/* Change elements in the first anonymous struct
* and verify change in the second anonymous struct
*/
vector.z = 16.0f;
printVector2D(vector.v1); // nothing changes here, prints 1.0 and 2.0
printVector2D(vector.v2); // 16.0 and 4.0
// memory address of float z is aligned with Vector2D v2.x [first element in v2]
return 0;
}