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

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

void print_point(const char* name, Point p) {
    printf("%s is a point at x=%d, y=%d\n", name, p.x, p.y);
}

int main(int argc, char* argv[]) {
    // NAMED INITIALIZER
    Point p1 = { .x = 5, .y = 6 };
             //└───────┬────────┘
             //  named initializer
    
    Point p2 = p1;   // regular initializer
    
    printf("p2 is a point at x=%d, y=%d\n", p2.x, p2.y);

    // Suppose we want to set p1 to x=3, y=4.

    // WRONG WAY - named initializer is only for initializing (initial value) on the line
    // where the variable is declared.
    // p1 = { .x = 3, .y = 4 };   // This is not a declaration.  It is an assignment.

    // RIGHT WAY:  COMPOUND LITERAL
    p1 = (Point) { .x = 3, .y = 4 };
    print_point("p1", p1);
    print_point("Mr. Compound Literal", (Point) { .x = 500, .y = 600 });

    // For an assignment, this is equivalent to assigning each field individually.
    // p1.x = 3
    // p1.y = 4
    // Easier to notice if you missed a field.
    // You could have a compound literal nested inside of another.
    // You could pass a compound literal to a function.
    return EXIT_SUCCESS;
}

/*
compound_literal.c: In function ‘main’:
compound_literal.c:25:7: error: expected expression before ‘{’ token
  p1 = { .x = 3, .y = 4 };   // This is not a declaration.  It is an assignment.
       ^
 */

/* vim:set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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