Reputation: 57
Is it possible to do something like this with the C preprocessor? If it's possible, what is the correct syntax? I would expect to see "5" as an answer, but I am getting "7". Thank you
#include <stdio.h>
#define ENABLE_FEATURE_1 true
#define ENABLE_FEATURE_2 false
#define ENABLE_FEATURE_3 true
#if (ENABLE_FEATURE_1 == true)
#define FT_BIT_0 1
#else
#define FT_BIT_0 0
#endif
#if (ENABLE_FEATURE_2 == true)
#define FT_BIT_1 2
#else
#define FT_BIT_1 0
#endif
#if (ENABLE_FEATURE_3 == true)
#define FT_BIT_2 4
#else
#define FT_BIT_2 0
#endif
#define ENABLED_FEATURES (FT_BIT_0 + FT_BIT_1 + FT_BIT_2)
int main() {
printf("Enabled Features: %i", ENABLED_FEATURES);
return 0;
}
Upvotes: 3
Views: 122
Reputation: 60056
Yes. But you need defines for true
and false
(or at least true
), otherwise the preprocessor will treat such unresolvable tokens in preprocessor conditionals as 0 (see 6.10.1p4), which is why you're getting 7 not 5 in your output (both true
and false
are treated as 0
in the conditionals and since 0 == 0
, all BIT macro get set to their non-zero versions).
#include
ing <stdbool.h>
will provide the defines. They are guaranteed to be (7.18):
#define true 1
#define false 0
Upvotes: 2