#include#include typedef enum {TYPE_INTEGER, TYPE_STRING, TYPE_DOUBLE, TYPE_UNSET} data_type_t;struct Data { char *name; int num; data_type_t type; union { int ivalue; double dvalue; char *cstr; }defval;};struct Data opt[] = { {"Option1", 1, TYPE_UNSET}, { .name = "Option2", .num = 2, .type = TYPE_DOUBLE, .defval.dvalue = 0.123 }, { num:3, name:"Option3", type:TYPE_STRING, .defval.cstr = "hahaha" }};int main(int argc, char *argv[]){ int i; size_t dlen = sizeof(opt)/sizeof(struct Data); printf("dlen = %u\n", dlen); for (i = 0; i < dlen; i++) { printf("i = %u, name = %s, type = %u, num = %d ", i, opt[i].name, opt[i].num, opt[i].type, opt[i].num); if (opt[i].type == TYPE_DOUBLE) printf(" defvalue = %f\n", opt[i].defval.dvalue); if (opt[i].type == TYPE_STRING) printf(" defvalue = %s\n", opt[i].defval.cstr); if (opt[i].type == TYPE_UNSET) printf("\n"); } return 0;}
编译输出:
dlen = 3i = 0, name = Option1, type = 1, num = 3 i = 1, name = Option2, type = 2, num = 2 defvalue = 0.123000i = 2, name = Option3, type = 3, num = 1 defvalue = hahaha