You are on page 1of 17

C++

Struct, Union & Enumerations


Outline
1. Data alignment
2. Size of Struct
3. Access Members of a Structure
4. Struct & Pointer
5. Struct & Union in Embed
6. Function in Struct
7. Nested Structure
8. Typedef
Struct, Union & Enum
• Struct and union

• Difference struct and union


The fundamental difference between the two is
how data is allocated in memory
Struct, Union & Enum
• Union example
Struct, Union & Enum
• Enum example
Data alignment
CPU truy cập vào memory theo từng block một, kích thước của mỗi block
có thể là 2, 4, 8, 16 hoặc 32 bytes

• Memory access granularity: kích thước mỗi block


• Aligned address: những địa chỉ là vị trí bắt đầu của một block (có giá trị
chia hết cho kích thước của một block)
• Unaligned address: những địa chỉ không nằm ở vị trí bắt đầu của một
block (có giá trị không chia hết cho kích thước của một block)
• Padding: Trình biên dịch sẽ cố gắng duy trì việc căn chỉnh của các phần
tử dữ liệu bằng cách chèn các ô nhớ không sử dụng giữa các phần tử
Data alignment - Example
Size of Struct
Is sizeof for a struct equal to the sum of sizeof of each member?
Reply: có thể có hoặc không phục thuộc vào các member trong struct và data
alignment của trình biên dịch
Access Members of a Struct
Array elements are accessed using the Subscript variable, Similarly
Structure members are accessed using dot [.] operator.
Struct & Pointer
Structures are often accessed through pointers using the −> (struct
pointer dereference) operator.
Struct & Union in Embed (3)
• Unions are also used to extract small blocks of data from a larger one:
Struct & Union in Embed (4)
 Real Life Applications of Structs and
Unions in Embedded Systems
• Access to Bits, Nibbles and Bytes of
Variables
Function in Struct
• Member functions inside the
structure

• Constructor creation in structure


Nested Structure (1)
• A nested structure in C/C++ is a structure
within structure. One structure can be
declared inside another structure in the
same way structure members are declared
inside a structure
• The structure can be nested in the
following different ways
• By separate nested structure
Nested Structure (2)
• By embedded nested structure: Using this method, allows to declare
structure inside a structure and it requires fewer lines of code.

The drawback in nested structures are


• Independent existence not possible
• Cannot be used in multiple data
structures
Typedef
• Using typedef command, you can define your own variable type

• ulong name as an alias for unsigned long. Now we can use ulong to declare
variables with unsigned long type.
• The same thing applies with struct and union:

• Now we can use sname to declare variables:


Thank you

By ThucNguyen

You might also like