-
Notifications
You must be signed in to change notification settings - Fork 160
/
struct_operators.c
91 lines (69 loc) · 1.83 KB
/
struct_operators.c
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
# Struct operators
*/
#include "common.h"
int main(void) {
/*
# Assign structs
# = for struct
Assigns fields one by one.
*/
{
struct S { int i; float f; };
struct S s = { 1, 1.0 };
struct S s2 = { 2, 2.0 };
s = s2;
assert(s.i == 2);
assert(s.f == 2.0);
}
/*
Assignment to an initializer only works for initialization.
We use a C99 compound literal to achieve the same effect however.
*/
{
struct S { int i; };
struct S s;
/*s = { 1 };*/
/*s = { .i = 1 };*/
}
/*
# == for struct
# Compare structs
Does not exist.
There have been failed proposals.
http://stackoverflow.com/questions/141720/how-do-you-compare-structs-for-equality-in-c
*/
{
struct S { int i; };
struct S s = { 1 };
struct S s2 = { 1 };
/*assert(s == s2);*/
/*
# memcmp structs
May not work because the padding is undefined, unless you memset it beforehand.
*/
}
/*
Inequalities do not exist either: `<` `>` `<=` `>=`
Here there is a stronger rationale than for `==`:
if `s.a < s2.a` and `s.b > s2.b`, what does `s < s2` eval to?
I.e.: what is the precedence of fields?
*/
/*
# sizeof for struct
# struct size
The way data is packed in a struct is not specified in the standard
Common compiler strategy: align data to 32 bits
which makes access faster, using slightly more memory.
*/
{
struct S {
char c;
int i;
};
/* Likely to be 8 on a 2013 32 bit machine. */
printf("struct sizeof = %zu\n", sizeof(struct S));
assert(sizeof(char) + sizeof(float) <= sizeof(struct S));
}
return EXIT_SUCCESS;
}