cpp hacking: bump FOO by 1

Fred Wright fw at fwright.net
Thu Sep 3 21:18:29 UTC 2020


On Thu, 3 Sep 2020, Hal Murray wrote:

> I don't see how to use your master/entry macros to solve my problem.

I didn't mean for those to be usable as is, but just as an illustration of 
the concept.  YMMV.

> The current code has only one table but it needs a symbol for the offset of
> each slot in the table.  Those symbols are used in a giant select.

In my example, the symbols are defined as enums, which handles the "bump 
FOO by 1" issue straightforwardly.  In general, enums are better than 
macros for compile-time constants anyway, for a number of reasons, but 
people tend to continue to use macros because "it's traditional", partly 
from the days before enums.

The CS_MAXVAL item I included is to get the range for a possible range 
check in the code.  Unfortunately, C doesn't have a built-in way to obtain 
that (sizeof(enum foo) isn't what you want).  Defining a value in this way 
makes it appear to be an additional legal value (which it isn't), which 
can then provoke compiler warnings if a switch statement doesn't include a 
case for it (or a default).  So you sometimes need to add an unreachable 
default case just to silence the warning.  Though in some cases, it can be 
arranged for the default entry to act as the range check (in which case 
you might not even need the explicit MAXVAL).

> I think I can rearrange the current code to avoid that select.  The idea is
> that the table gets a tag and union slot where we can put a procedure that
> does what was the code at that branch of the select.  Most of them would be
> handled by a handful procedures.  A few would need special routines.

Whether it's a table or a switch statement, the content can be constructed 
with this technique.  You just have to include enough arguments in the 
entry macros to cover everything needed.  If there are cases which are 
sufficiently different to make this difficult, there could be more than 
one master macro to cover different categories of cases, perhaps not even 
using a master macro for some significantly oddball cases in the switch 
(but still using it elsewhere).

Fred Wright


More information about the devel mailing list