HaggarTheHorrible
HaggarTheHorrible

Reputation: 7403

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
//#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?

Upvotes: 0

Views: 313

Answers (5)

smcameron
smcameron

Reputation: 1327

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?

Upvotes: 1

unwind
unwind

Reputation: 399813

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

Upvotes: 1

Martin Beckett
Martin Beckett

Reputation: 96109

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.

Upvotes: 1

mouviciel
mouviciel

Reputation: 67829

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

Upvotes: 1

SLaks
SLaks

Reputation: 887433

#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

Upvotes: 4

Related Questions