Default values in a C Struct Default values in a C Struct c c

Default values in a C Struct


While macros and/or functions (as already suggested) will work (and might have other positive effects (i.e. debug hooks)), they are more complex than needed. The simplest and possibly most elegant solution is to just define a constant that you use for variable initialisation:

const struct foo FOO_DONT_CARE = { // or maybe FOO_DEFAULT or something    dont_care, dont_care, dont_care, dont_care};...struct foo bar = FOO_DONT_CARE;bar.id = 42;bar.current_route = new_route;update(&bar);

This code has virtually no mental overhead of understanding the indirection, and it is very clear which fields in bar you set explicitly while (safely) ignoring those you do not set.


You can change your secret special value to 0, and exploit C's default structure-member semantics

struct foo bar = { .id = 42, .current_route = new_route };update(&bar);

will then pass 0 as members of bar unspecified in the initializer.

Or you can create a macro that will do the default initialization for you:

#define FOO_INIT(...) { .id = -1, .current_route = -1, .quux = -1, ## __VA_ARGS__ }struct foo bar = FOO_INIT( .id = 42, .current_route = new_route );update(&bar);


<stdarg.h> allows you to define variadic functions (which accept an indefinite number of arguments, like printf()). I would define a function which took an arbitrary number of pairs of arguments, one which specifies the property to be updated, and one which specifies the value. Use an enum or a string to specify the name of the property.