C Designated Initializers

Static Struct Initialization

struct student {
    int roll;
    int class;
    char name[50];
};

student mark = {
    .name = "Mark",
    .class  = 10,
    .roll  = 1038
};

GCC: 6.26 Designated Initializers
GCC 4.4.1: 5.23 Designated Initializers
C: Structure Initialization (Advanced)

Static Array Initialization

#define ADDRESS1 0x01
#define ADDRESS2 0x02
#define ADDRESS3 0x03
#define ADDRESS4 0x04

const static uint32_t address_map[] = {
    [0] = ADDRESS1,
    [1] = ADDRESS2,
    [2] = ADDRESS3,
    [3] = ADDRESS4
};

#define REGISTER_MAP(name, reg) [name] = reg

#define NAME1    0x03
#define NAME2    0x01
#define NAME3    0x02
#define NAME4    0x04

#define ADDRESS1 0x01
#define ADDRESS2 0x02
#define ADDRESS3 0x03
#define ADDRESS4 0x04

const static uint32_t address_map[] = {
    REGISTER_MAP(NAME1, ADDRESS1),
    REGISTER_MAP(NAME2, ADDRESS2),
    REGISTER_MAP(NAME3, ADDRESS3),
    REGISTER_MAP(NAME4, ADDRESS4)
};

How to initialize an array in C
Initialization of arrays
c: initializing arrays

Leave a Reply

Your email address will not be published.