Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ #if #elif #endif don't seem to work

Can somebody please tell me what I'm doing wrong?

#include <iostream>
using namespace std;

int main() {

#define myvar B

#if myvar == A
        cout << "A" << endl;
#elif myvar == B
        cout << "B" << endl;
#else
        cout << "Neither" << endl;
#endif
}

The output is A but obviously I was expecting B

like image 210
rmp251 Avatar asked Dec 03 '25 04:12

rmp251


1 Answers

This:

#if myvar == A

expands to:

#if B == A

Quoting the C++ standard:

After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers and keywords, except for true and false, are replaced with the pp-number 0, and then each preprocessing token is converted into a token.

so that's equivalent to:

#if 0 == 0

which is of course true.

The == operator in preprocessor expressions doesn't compare strings or identifiers, it only compares integer expressions. You can do what you're trying to do by defining integer values for A, B, and myvar, for example:

#define A 1
#define B 2
#define myvar B

#if myvar == A
    cout << "A" << endl;
#elif myvar == B
    cout << "B" << endl;
#else
    cout << "Neither" << endl;
#endif
like image 173
Keith Thompson Avatar answered Dec 04 '25 19:12

Keith Thompson