1

I want to conditionally compile my code with macros. The usual approach outlined in these questions: 1 2 3 4 5 is to #define A_MACRO "and give it a value", and then use #ifdef or #if defined to determine if it was defined. Example:

//#define A 0
#define B 0
//#define C 0

#ifdef A
    /*A stuff*/
#elif defined(B)
    /*B stuff*/
#else 
    /*C stuff*/
#endif

I just had the idea to do something like:

#define A 0
#define B 1
#define C 2

#define LETTER B

#if LETTER == A
    /*A stuff*/
#elif LETTER == B
    /*B stuff*/
#else
    /*C stuff*/
#endif

Are there any benefits or drawbacks of using one over the other? Personally I think the second is more readable and doesn't require to comment out macros if you are not using them. Also having to give macros a value that isn't used in any way is also counter-intuitive.

sneaker
  • 51
  • 5
  • **Comments have been [moved to chat](https://chat.stackoverflow.com/rooms/253669/discussion-on-question-by-sneaker-benefits-and-drawbacks-of-doing-conditional-co); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed. – Samuel Liew May 16 '23 at 01:14

2 Answers2

1

#define values are picked up by the compiler's pre-processor stage and as such are processed when you click to compile your code.

You're not using them here as MACROs in the sense that they do not replace code e.g., #define SUM(x,y) x+y, but instead you're using them to indicate code blocks that should be processed or not by the compiler.

Typically you would include these as part of your pre-processor directives and not define them within your code.

With pre-processor directives no value is required instead you could use A, B or C - although I'd suggest something longer and more meaningful.

Then you would use your first code block

#ifdef A
    /*A stuff*/
#elif defined(B)
    /*B stuff*/
#else 
    /*C stuff*/
#endif

Used in this manner code that is not within the applicable #if .. #endif logic is excluded from the compilation process. Thus if A is defined no B or C applicable code is compiled.

ChrisBD
  • 9,104
  • 3
  • 22
  • 35
1

Are there any benefits or drawbacks of using one over the other?

I believe the second one should be preferred when one option is choosing multiple paths because:

  • there is a single place of configuration - LETTER
  • all states are enumerated in one place and can be documented
KamilCuk
  • 120,984
  • 8
  • 59
  • 111