Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values in a C Struct

I have a data structure like this:

struct foo {     int id;     int route;     int backup_route;     int current_route; } 

and a function called update() that is used to request changes in it.

update(42, dont_care, dont_care, new_route); 

this is really long and if I add something to the structure I have to add a 'dont_care' to EVERY call to update( ... ).

I am thinking about passing it a struct instead but filling in the struct with 'dont_care' beforehand is even more tedious than just spelling it out in the function call. Can I create the struct somewhere with default values of dont care and just set the fields I care about after I declare it as a local variable?

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

What is the most elegant way to pass just the information I wish to express to the update function?

and I want everything else to default to -1 (the secret code for 'dont care')

like image 1000
Arthur Ulfeldt Avatar asked Apr 14 '09 20:04

Arthur Ulfeldt


People also ask

How do you give a struct a default value?

Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members. Another way of assigning default values to structs is by using tags.

Can you initialize values in a struct in C?

No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).

Are struct members initialized to zero?

If a structure variable has static storage, its members are implicitly initialized to zero of the appropriate type. If a structure variable has automatic storage, its members have no default initialization.

Does struct have default constructor?

C# does not allow a struct to declare a default, no-parameters, constructor. The reason for this constraint is to do with the fact that, unlike in C++, a C# struct is associated with value-type semantic and a value-type is not required to have a constructor.


1 Answers

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.

like image 141
hlovdal Avatar answered Oct 10 '22 09:10

hlovdal