31

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

45

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
Sign up to request clarification or add additional context in comments.

5 Comments

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.
@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).
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.
I've done most of my programming on the Windows platform using Microsoft tools and code, so maybe I've picked up their habits.
you forget about say sizeof(int) . you can't do this no-braces way haha
13

#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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.