[LCP]global variable alternative

Vincent Penquerc'h Vincent.Penquerch at artworks.co.uk
Thu Apr 4 02:56:05 UTC 2002


> Many of these options are global variables since I reference 
> them often 
> within deep lying functions.

I was about to say "One way is to write a small class, eg Config",
but I just noticed we're on the C list ;)

How about using strings, but hashing them to get an identifier
that you use for more speed. This identifier could be an index
to the table of all your options, thus yielding fast access.

If in function foo you need to access option bar a lot, you can do:

void foo()
{
  static option_id bar=options_hash("bar"); // note the static
  /* use bar a lot */
}

options_hash would then keep a hash table of all your option
strings, create one when an unknown option is requested, and
return the exising entry (eg an index is a table where you
allocate new option data at the back, hence getting a linear
table indexed by all the indices you send back) when the string
is there already (from a previous call to options_hash with
this same string).
The static is very important there, as the point is to call the
hash function very few times (even if a hash lookup is supposedly
O(1)). The hashing will be done only at the first invocation.

You would of course need other routines like:

option_t *options_get(option_id);
void options_clear();

and possibly others:

int options_save(const char *filename);
int options_load(const char *(filename);

-- 
Vincent Penquerc'h 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.linux.org.au/pipermail/linuxcprogramming/attachments/20020404/d47d17c3/attachment.htm 


More information about the linuxCprogramming mailing list