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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

typedef struct {
    int x;
    int y;
} Point;

int main(int argc, char* argv[]) {
    //_______________________________________________________________________________
    // NAMED INITIALIZER
    Point p1 = { .x = 5, .y = 7 };
    //         └────────┬───────┘
    //            named initializer

    //_______________________________________________________________________________
    // COMPOUND LITERAL
    p1 = (Point) { .x = 6, .y = 8 };
    //   └───────────┬────────────┘
    //        compound literal
    //
    // This compound literal represents an entire Point object.  You can assign or pass it just
    // like you would if you had a variable containing a Point object.
    
    //_______________________________________________________________________________
    // PITFALL: Compound literals and named initializers are not the same.
    //
    // p1 = { .x = 6, .y = 8 };  // WRONG ... gcc error: expected expression before ‘{’ token
    //
    // Remember: Use a named initializer only when initializing a struct object (setting its fields
    // to values for the first time).
    //
    // Do not use a named initializer when assigning a new value to a struct object (i.e., its
    // fields), or for struct objects on the heap.

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2023 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.