Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Whats the appropriate place to define a lookup table?



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.

like image 814
Rishabh Puri Avatar asked Mar 24 '23 14:03

Rishabh Puri

2 Answers

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

like image 171
lucasg Avatar answered Apr 01 '23 20:04


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]; 
like image 23
Mats Petersson Avatar answered Apr 01 '23 20:04

Mats Petersson