Sunday, September 7, 2008

useanenum

Barry Schwarz 07 Sep, 09:04
Re: Increment a number in compile time macro
On Sat, 6 Sep 2008 23:54:08 -0700 (PDT), Bin Chen
wrote:

>switch(i) {
>case 1:
> break;
>case 2:
> break;
>[...]
>case N:
> break;
>
>}
>
>Now, after some time I want to add a 'case 2' between case 1 and case
>2, the result means every case number after case 2 need to be
>incremented by 1, it there a macro tricks to make life easier? Such
>as:
>
>switch(i) {
>case AUTO_INC_MACRO:
> break;
>case AUTO_INC_MACRO:

Macros don't perform calculations. They only perform text
substitution. And a subsequent appearance of a macro in your code
will not have access to the result of a previous appearance.

However, you can do what you want with an enum. Something of the form
enum {CASE1=1, CASE2, ..., CASEN};
and change each case label to
case CASE1:
...
case CASE2:
etc.

Later, when you want to insert a case between CASE1 and CASE2, change
you enum to
enum {CASE1=1, CASE1A, CASE2, ..., CASEN};
and insert the new block of code immediately before the CASE2 label.

To eliminate the rampant confusion after a half-dozen insertions where
CASE6 may be 7 while CASE10 is 13, I would suggest using identifiers
that are suggestive of the function to be performed rather than their
numeric value. Something like
enum {INSERT=1, DELETE, EDIT, COMPUTE};
and then you could later amend it to
enum {INSERT=1, DELETE, EDIT, PRINT, COMPUTE};

0 comments:

~/.history