开发者

C Preprocessor: #define in C... advice

I'm making a big C project and I have never come across a situation like this before so, I need your advice.

What is your opinion? Is it okay to have the constants defined within conditional preprocessors like I have done below or you advise me to do this some other way?

#define NUM_OCTAVES_4
//#defin开发者_C百科e NUM_OCTAVES_5

    #ifdef NUM_OCTAVES_4
     #define OCTAVES 4
     const unsigned char borders [4] = {11, 26, 50, 98};
    #elif NUM_OCTAVES_5
     #define OCTAVES 5
     const unsigned char borders [5] = {11, 26, 50, 98, 194};
    #endif

Any drawbacks if I do it this way?


#define OCTAVES 4

#if OCTAVES == 4
 const unsigned char borders [4] = {11, 26, 50, 98};
#elif OCTAVES == 5
 const unsigned char borders [5] = {11, 26, 50, 98, 194};
#endif


Of course it is okay. This is the point of conditional compilation.


Is octaves 4/5 so fundemental that you would be compiling different versions of the app? If you were selling it would it be a different product?

The correct way would be to allocate borders at run time with malloc, but if this is just a simple excercise you migth not want to learn about that yet.

Or you could make borders[5] and set the last value to 0 or some easily detectable end of octaves value.


It is more DRY, i.e. less repetitive, to be a bit more clever:

#define OCTAVES 4
/*define OCTAVES 5 */

 const unsigned char borders [] = {11, 26, 50, 98,
#if OCTAVES == 5
  194
#endif
 };

This way, you don't need to the four first values the same in two "branches" of the code.

Or, if you find that offensive, factor it out into a macro and repeat that, instead:

#define BORDERS4 11, 26, 50, 98

#if OCTAVES == 4
const unsigned char borders[] = { BORDERS4 };
#else if OCTAVES == 5
const unsigned char borders[] = { BORDERS4, 198 };
#endif


Why not just have the "5" version of the array, and then have int noctaves = 4; or some other way to ignore the last octave if you only want 4?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜