views:

63

answers:

3

I have a requirement something like

void doSomeThing(int x)
{
.....
}

void fun()
{

 #ifdef XXXX_1_YYYY
doSomeThing(XXXX_1_YYYY);
 #endif //XXXX_1_YYYY

 #ifdef XXXX_2_YYYY
doSomeThing(XXXX_2_YYYY);
 #endif //XXXX_2_YYYY

 #ifdef XXXX_3_YYYY
 doSomeThing(XXXX_3_YYYY);
 #endif //XXXX_3_YYYY

 #ifdef XXXX_4_YYYY
 doSomeThing(XXXX_4_YYYY);
 #endif //XXXX_4_YYYY

....
upto XXXX_20_YYYY

}

Is there anyway i can reduce the typing of this upto 20 using some macro expansion technique or any other solution?

MACRO definition can be something like this

#define XXXX_1_YYYY 10
#define XXXX_2_YYYY 20
#define XXXX_3_YYYY 30
#define XXXX_4_YYYY 40
...
#define XXXX_20_YYYY 200

Each of the #ifdef are not mutually exclusive. The code is in c++

A: 

A trivial answer perhaps, but if they're all mutually exclusive, then using #elif will save you a lot of #endifs.

It's hard to know a good way to avoid this without knowing more about what you're actually trying to do. Are all those functions in the same file, each with a #if around it?

Will Dean
A: 

I can't see a way to do it with standard C preprocessor.

Maybe the problem can be restated. Can you can show us broader context?

And remember that, instead of abusing C preprocessor, you can always generate code with some other tool, like m4, perl, bash, etc. Or JScript, VBScript, etc. on Windows. If your build system permits, that is.

Tomek Szpakowicz
A: 

If there is a special value of XXXX_n_YYYY (like NULL for a pointer value, -1 for int, etc), you can use that special value to flag that constant as "not defined" (instead of leaving it as undefined). Then you can use some code that looks like:

void fun()
{
    size_t i;
    static XYXX_type job_que[] = { XXXX_1_YYYY, XXXX_2_YYYY, .... };

    for (i=0; i!=ARRAY_SIZE(job_que); ++i)
    {
        if (job_que[i] != SPECIAL_VALUE) do_something(job_que[i]);
    }
}

It is very hard to come up with something better with the given amount of detail.

Dysaster
I want to this to be compile time, not run time
In that case, see matt's comment above. The one you have is the best you can achieve. With C++, you can use do_something(void) overloading with empty function, and defining the undefined ones to be nothing (to prevent errors), you can do the same loop without the if and the array, but that's the best I can come up with.
Dysaster