41 lines
512 B
Markdown
41 lines
512 B
Markdown
|
|
---
|
||
|
|
tags:
|
||
|
|
- C
|
||
|
|
---
|
||
|
|
|
||
|
|
A `struct` is a custom, user-defined type, in constrast to the primitive types
|
||
|
|
(`int`, `char`, `float` etc). They are known as **compound types**.
|
||
|
|
|
||
|
|
## Usage
|
||
|
|
|
||
|
|
Define the custom type:
|
||
|
|
|
||
|
|
```c
|
||
|
|
struct Person {
|
||
|
|
int age;
|
||
|
|
float height;
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
Then to apply the type to a variable:
|
||
|
|
|
||
|
|
```c
|
||
|
|
struct Person thomas
|
||
|
|
```
|
||
|
|
|
||
|
|
And define the sub-properties:
|
||
|
|
|
||
|
|
```c
|
||
|
|
thomas.age = 37
|
||
|
|
thomas.height = 5.8
|
||
|
|
```
|
||
|
|
|
||
|
|
Alternatively do all together:
|
||
|
|
|
||
|
|
```c
|
||
|
|
struct Person thomas = {
|
||
|
|
.age = 37,
|
||
|
|
.height = 5.8
|
||
|
|
}
|
||
|
|
```
|