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

// this is not allocating space
// whenever the compiler sees "struct Point", this is what it means
struct Point { // 8 bytes
    int x; // 4 bytes
    int y; // 4 bytes
};


struct Point make_struct(int y, bool setX) {
    struct Point p_ret = { .y = y };
    if (setX) {
        p_ret.x = y;
    }
    return p_ret;
}

void print_point(struct Point p) {
    printf("(p.x, p.y) == (%d, %d)\n", p.x, p.y);
}

int main(int argc, char* argv[]) {
    int x = 7;
    // .x means it is struct Point's x, not my local x
    struct Point p1 = { .y = 4, .x = 5 };
    // bad code quality but equivelent: what fields am I setting?
    // struct Point p = { 5, 4 };

    printf("x == %d\n", x);
    print_point(p1);

    struct Point p2 = p1;
    p1.y = 3; // modifies p1, but the copy p2 is unchanged
    print_point(p1);
    print_point(p2);

    struct Point p3 = make_struct(7, true); 
    struct Point p4 = make_struct(2, false);    
    printf("(p3.x, p3.y) == (%d, %d)\n", p3.x, p3.y);
    printf("(p4.x, p4.y) == (%d, %d)\n", p4.x, p4.y);

    // initalizes by manually setting each field
    struct Point p5;
    p5.x = 5;
    p5.y = 7;
    print_point(p5);

    // this is the same as p5
    struct Point p6;
    p6 = (struct Point){ .x = 5, .y = 7 };
    // this will not work: p6 = { .x = 5, .y = 7 };
    print_point(p6);

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

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