15

In my project, the program can do one thing of two, but never both, so I decided that the best I can do for one class is to define it depending of a #define preprocessor variable. The following code can show you my idea, but you can guess that it does not work:

#ifdef CALC_MODE
typedef MyCalcClass ChosenClass;
#elifdef USER_MODE
typedef MyUserClass ChosenClass;
#else
static_assert(false, "Define CALC_MODE or USER_MODE");
#endif

So I can do

#define CALC_MODE

right before this.

I can resign the use of static_assert if needed. How can I do this?

4
  • 3
    You can use #if defined(CALC_MODE) and #elif defined(USER_MODE) Commented Aug 7, 2021 at 22:47
  • 3
    Are you looking for $elif defined(...)? You may also find the #error directive interesting. Commented Aug 7, 2021 at 22:48
  • @RetiredNinja that is correct! Commented Aug 7, 2021 at 22:51
  • @StoryTeller-UnslanderMonica Right, actually better than static_assert in this case, because it will always be false Commented Aug 7, 2021 at 22:59

2 Answers 2

23

Here's a suggestion, based largely on comments posted to your question:

#if defined(CALC_MODE)
    typedef MyCalcClass ChosenClass;
#elif defined(USER_MODE)
    typedef MyUserClass ChosenClass;
#else
    #error "Define CALC_MODE or USER_MODE"
#endif
5
  • 2
    defined is an operator, not a function, like sizeof, so the parentheses are unnecessary and are just clutter. It is better that students see it is an operator that directs the compiler to do something rather than that it is a function that is called. Commented Aug 7, 2021 at 23:14
  • 5
    @Eric It's a Community Wiki, so feel free to edit. However, I think you'll find a near 50:50 split on the use of sizeof Eric versus sizeof(Eric). Commented Aug 7, 2021 at 23:19
  • 7
    Yeah, definitely not cut-and-dry. I personally always use parens on sizeof and defined, just because it looks a lot cleaner in my mind. There are lots of folks in both camps. Commented Aug 7, 2021 at 23:20
  • I've done most of my programming on the Windows platform using Microsoft tools and code, so maybe I've picked up their habits. Commented Aug 7, 2021 at 23:22
  • you forget about say sizeof(int) . you can't do this no-braces way haha Commented Aug 8, 2021 at 0:05
3

#elifdef and #elifndef are officially supported since C23 and C++23.

But these standards are not yet released (as of July 2023) and the new features are not yet widely adopted by compilers, so you are still better off with #if defined() for now.

Not the answer you're looking for? Browse other questions tagged or ask your own question.