While wrting an application , I wrote a single lookup table (an integer array)
While performing lookup, I have written an api which takes the input and returns an output, and the lookup table is defined in that api.?
Should I initialize that lookup array in global scope as const array (places it in data segment)
What is the advantage of initializing it in an api / defining it in data segment ?
PS: the lookup table is less than size 50.
The principle of encapsulation says that every "class" (or object, or struct, ..) must disclose the least amount on information about their inner structure, so it depends on your design.
It's generally a good rule to declare the lookup table as const array : the compiler will optimize the array (for example by putting it in low-speed write time and good access-time memory banks).
If you need to access the lookup table from code located in several files, declare your table in a separate file xxxLookupTable.c
, write a wrapper around it (like xxxLookupTableManager
) in xxxLookupTable.h
and link the header wherever the lookup is needed
My typical approach would be:
int lookup_stuff(int stuff)
{
static const int table_of_stuff[] = { 1, 2, 7, 8, 14, 20, 24, 29, ... };
assert(stuff < sizeof(table_of_stuff)/sizeof(table_of_stuff[0]));
/* if stuff comes from an external source, such as a user modifiable text file,
the assert should be converted to an "if" so that it's present in all
versions of the code, not just debug builds */
return table_of_stuff[stuff];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With