forked from cirosantilli/cpp-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compound_struct_literal.c
59 lines (46 loc) · 1.29 KB
/
compound_struct_literal.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
/*
# Compound struct literal
Create literals for structs.
They behave exactly like initialized objects, except that they have no variable name.
*/
#include "common.h"
int main() {
struct S { int i; int j; };
/* Basic example. */
{
struct S s;
s = (struct S){1, 2};
/* Remember that this would fail. */
/*s = {1, 2};*/
assert(s.i == 1);
assert(s.j == 2);
}
/* With designated initializer syntax. */
{
struct S s;
s = (struct S){.j = 2, .i = 1};
assert(s.i == 1);
assert(s.j == 2);
}
/* They do generate lvalues. */
{
struct S *sp;
sp = &(struct S){1, 2};
assert(sp->i == 1);
assert(sp->j == 2);
/* Unlike string literals, they can be modified. */
sp->i = 3;
sp->j = 4;
assert(sp->i == 3);
assert(sp->j == 4);
}
/*
# Lifetime of compound struct literals
- if inside a function, automatic associated with current block.
- otherwise, static
http://stackoverflow.com/questions/14955194/lifetime-of-referenced-compound-array-literals
*/
/* Can also be used to initialize variables, although that is useless. */
struct S s = (struct S){1, 2};
return EXIT_SUCCESS;
}