This does not answer your question directly, but illustrates how change to a struct
can be managed without concern due to adding members over time.
(Note, these ideas do NOT apply when REMOVING members)
A substantial benefit of using the struct
construct (over using discrete types) is precisely what you are asking about: ability to add members without breaking your code The struct
type can insulate legacy revisions of code from the need to add additional required variables. That is, you can add members to a struct that is defined globally, without forcing change to the prototype of any function that includes it in its argument list.
For example: given your scenario with the following structs:
(Note, I am using typedef
so that the declarations will be shorter in argument list, and added real members)
Here is your original scenario:
typedef struct
{
int a1;
int a2;
}A;
typedef struct
{
int b1;
int b2;
}B;
typedef struct //small change for less text in prototypes
{
A a;
B b;
}AB;
Here are two functions that use the struct AB
This one was written for use before any modifications to original AB: (and does not currently need new member)
void func1(AB var_old)
{
var_old.a.a1 = 3;
var_old.a.a2 = 3;
var_old.b.b1 = 4;
var_old.b.b2 = 4;
//Note: if var_old.b.b3 is ever needed here, it is available without changing prototype
}
sometime later a function is created (or modified) that requires a new variable
Add member to struct B:
typedef struct
{
int b1;
int b2;
int b3;
}B;
Use it here:
void func2(AB var_new)
{
var_new.a.a2 = 10;//pre-existing member
var_new.b.b3 = 4; //new member
}
The prototype argument list did not change, avoiding the need to edit every function that uses AB
.