views:

107

answers:

5

Hi Guys, 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
//#define 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?

+4  A: 
#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
SLaks
`#else` `#error Invalid value for OCTAVES`
BlueRaja - Danny Pflughoeft
If you change that to `const unsigned char border[OCTAVES] =` for each then it will be even cooler.
nategoose
+1  A: 

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

mouviciel
+1  A: 

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.

Martin Beckett
+1  A: 

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?

smcameron
+1  A: 

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
unwind
However, it's uglier.
SLaks