Consider a C struct that represents an entry in a singly linked list. It contains a pointer to some arbitrary data, the size of that data, and a way to find the next Entry
typedef struct{
unsigned char *data
unsigned char dataSize
unsigned char nextEntry
} Entry;
Next, consider the following collection of entries and the data that they represent:
unsigned char dataA[3];
unsigned char dataB[16];
unsigned char dataC[17];
Entry entryA = {dataA, sizeof(dataA), 3}; //It's important for "3" to match up with the index of entryB once it's put into MasterList below.
Entry entryB = {dataB, sizeof(dataB), 4}; //Likewise
Entry entryC = {dataC, sizeof(dataC), 0}; //0 terminates the linked list
Entry emptyEntry = {(void*)0, 0, 0};
Entry MasterList[8] = {
entryA, //Index 0 - Contains dataA and points to Index 3 as the next Entry in a linked list
emptyEntry, //Index 1 - Unused (or used for something else)
emptyEntry, //Index 2 - Unused
entryB, //Index 3 - Contains dataB and points to Index 5 as the next Entry in a linked list
entryC, //Index 4 - Contains dataC and terminates the linked list
emptyEntry, //Index 5 - Unused
emptyEntry, //Index 6 - Unused
emptyEntry};//Index 7 - Unused
My Question:
Can you think of a way to figure out the value for “nextEntry” automatically at compile time? Right now there’s a huge potential for bugs if someone shuffles the order of the entries in the MasterList or adds some other data and offsets some of entries. We catch all of the bugs with unit testing or integration testing, but it’s inevitable that any change to the MasterList ends up getting checked in twice. Once when someone edits it and a 2nd time to patch up the linked list indicies when the code fails testing.
My initial instinct is “no, that’s idiotic” and “why would you even try this?” but I’ve seen some pretty impressive C-Macro wizardry in the past. I also believe that any macro wizardry would be even worse to maintain than the above, but I figure it’s worth a shot, right?
Clarification – I’m stuck with the MasterList array (and not a proper linked list) because the consumer of the information is expecting it to be this way. In fact, there’s other information in there that isn’t part of the linked list that needs to be at a fixed index. Then, on top of that, there’s this linked list data. The reason it’s a linked list is to make it somewhat immune to getting shoved around as other elements with fixed indices are added. For example, if it turned out that we needed to shove in a specific string at Index 3, entryB and entryC could get pushed out of the way, but could still be discovered by starting at the linked list head (fixed at Index 0) and walking the list.
It looks like there isn’t really a good way to do this with the tools available to the compiler or the pre-processor. I think the best way to do this is with a code generation tool that generate the array with the linked list already hooked up.