Yoda
Yoda

Reputation: 18068

How to make compilation fail if both or none preprocessor macro is defined

Friend asked me for help in C++. I do not use C++ only C#(WP,WPF,WinForms) and Java(Android).

The part of the task he has is when the macro STAR is defined he should draw a christmass tree with * (stars) when the macro EQ is defined he suppose to draw it with = (assign operator). If both or none is defined compilation has failed. Drawing christmass tree is easy task in any language but I have problems with those preprocessor macros.

#define STAR *
#define EQ =

#if !(defined(STAR) ^ defined(EQ)) 
   FAIL TO COMPILE?
#endif

How to check then in code which macro is defined and assign its' value to the char character;?

Upvotes: 8

Views: 4899

Answers (3)

Yoda
Yoda

Reputation: 18068

I did this task for him. The preprocessor instructions look like:

 #define STAR "*"
// #define EQ "="
 #if !(defined(STAR) ^ defined(EQ))
      #error "STAR XOR EQ have to be defined"
 #elif (defined(STAR))
        #define CHARACTER STAR
 #elif (defined(EQ))
        #define CHARACTER EQ
 #endif

Upvotes: 2

Shahbaz
Shahbaz

Reputation: 47563

There is a preprocessor directive for that:

#error "One and only one of STAR or EQ should be defined"

Upvotes: 9

Sean
Sean

Reputation: 62522

You want the #error pre-processor directive

Upvotes: 18

Related Questions