October 2017, rev. April 2020

C doesn't allow passing the name of a struct field as a parameter.

I noticed this when I wrote a function that traverses recursively a C struct. If field vmup_dyn is not NULL, keep traversing. This looks up symbols with dynamic scoping.

Later I wanted to to lookup symbols with lexical scoping. I wanted a function that does the same thing but uses a different field called vmup_lex. There's no built-in way to pass something to C that means "use this other struct field".

The only way to do this in C in a single function is manually. To pass an offset to the field as a number, somehow make sure the offset is what the compiler expects, and add the offset to the address of the variable.

Passing the name of a struct field as a parameter can be done with a macro. But although this is an advantage for macros, it's not the smallest solution. Using a macro creates two functions. It increases the total size of the compiled code.

A smaller solution, which the compiled languages I use today don't support, is to let functions accept the name of a struct field as a parameter. Same goes for arithmetic operators.