Given this simple C code:
struct {
struct a {
int foo;
};
struct b {
char *bar;
};
} s;
I am wondering whether there is a way to access a variable in one of the nested structures in a more compact way than s.a.foo = 5, for instance.
First, notice that your example is not standard C89 (but it is acceptable by some compilers when you ask for some language extensions. With GCC you’ll need to extend the accepted C dialect with the
-fms-extensionsflag to the compiler). You are using unnamed fields. A more standard way of coding would be:Back to your question, no, there is no other way. However, you might use preprocessor macros, whcih could help. For instance, assuming the above declarations, you could
and then you can code
s.afooinstead ofs.aa.fooYou might also define macros like
and then code
AFOO(s)Using such preprocessor macros does have some annoyance: with my example, you cannot declare anymore a variable (or formal argument, or field, or function) named
afooBut I am not sure you should bother. My personal advice & habit is to give longer and often unique names to fields (and also to name
struct a_stmystruct-ures). Take advantage of the auto-completion abilities of your editor. Don’t forget that your code is more often read than written, so use meaningful names in it.