user1638717
user1638717

Reputation: 161

How to use enum values to direct compilation with preprocessor directives

I want to select a portion of my code for compilation based on an enum value. So, how can I combine the use of enum with preprocessor directives to achieve this goal? An example is like the following:

#include <iostream>

enum CODE {BINARY, PERMUTATION, BYVALUE};

#define ENCODING(x) (x)

using namespace std;

int main()
{
    CODE code = PERMUTATION;
#if ENCODING(code) == BINARY
    cout << "code: BINARY" << endl;
#elif ENCODING(code) == PERMUTATION
    cout << "code: PERMUTATION" << endl;
#elif ENCODING(code) == BYVALUE
    cout << "code: BYVALUE" << endl;
#endif
    return 0;
}

Obviously, this is not correct to get my aim as it always takes the first #if statement and displays "code: BINARY". Is there any way to use the enum to control the compiled segments? Thank you.

Upvotes: 0

Views: 588

Answers (1)

nullptr
nullptr

Reputation: 11058

You are trying to control a compiling (preprocessing) process using a run-time variable value. It is not possible.

You should either select parts of your code to be compiled at a preprocessing stage (using #define), or you can write a switch statement that will select the needed encoding (if the code is constant, then an optimizing compiler will efficiently eliminate the switch).

Upvotes: 4

Related Questions