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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef struct {
int x;
int y;
} Point;
void print_point(Point p) {
printf("p.x == %d p.y == %d\n", p.x, p.y);
}
int main(int argc, char* argv[]) {
Point p1 = { .x = 5, .y = 6 }; // "NAMED INITIALIZER" -- only for first assignment
print_point(p1); // that comes on the same line as declaration.
Point p2 = p1;
print_point(p2);
// p1 = { .x = 7, .y = 9 }; // Named initializer does not work for a regular assignment.
// // GCC: "error: expected expression before ‘{’ token"
// You can use a compound literal in much the same ways that you could use a variable
// of that type, or a constant of a simple type (e.g., int, float, etc.).
// 1. assignment (like ↑)
// 2. pass to a function (useful for testing)
// 3. initializing an object on the heap (for append(…) and other linked list stuff)
//
// Where possible: Use compound literal to initialize objects on the heap, instead of
// field-by-field.
p1 = (Point) { .x = 7, .y = 9 }; // 1. assigning to a variable
print_point((Point) { .x = 7, .y = 9 }); // 2. calling a function
Point* a_p2 = malloc(sizeof(*a_p2));
*a_p2 = (Point) { .x = 3, .y = 4 }; // 3. initializing object on heap
// Not this:
// a_p2 -> x = 3;
// a_p2 -> y = 4;
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.