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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef struct {
int x;
int y;
} Point;
// COMPOUND LITERAL lets you assign an entire object, including all fields, at once.
// You can also pass it to a function.
//
// When setting all fields of an object, use a compound literal or named initializer,
// wherever possible, unless a specific, articulable reason not to.
int main(int argc, char* argv[]) {
// NAMED INITIALIZER
Point p1 = { .x = 5, .y = 6 }; // NAMED INITIALIZER
// COMPOUND LITERAL
p1 = (Point) { .x = 7, .y = 8 }; // COMPOUND LITERAL
printf("p1 contains x=%d, y=%d\n", p1.x, p1.y);
Point p2 = p1; // regular initializer (not a named initializer or compound literal)
p1 = (Point) { .x = 9, .y = 10 }; // COMPOUND LITERAL
p2 = p1; // regular assignment
// WRONG: Named initializer syntax does not work as a RHS¹ of an assignment.
// p1 = { .x = 7, .y = 8 };
return EXIT_SUCCESS;
}
// ¹ RHS = right-hand side
/* 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.