user1992416
user1992416

Reputation: 1

Using variables in the preprocessor directives

which global variable can be used in the preprocessor directive file.cpp

int variable = 1;
#if variable >= 1
    int a = 0;
#else 
    int a = 1;
#endif

or

file.cpp

const int variable = 1;
#if variable >= 1
    int a = 0;
#else 
    int a = 1;
#endif

or file.cpp

#include "header.h"
// extern in variable; in the header.h
#if variable >= 1
    int a = 0;
#else 
    int a = 1;
#endif

What are the rules which governs using the variables in the proprocessor directive? If a variable which can be consant folded, can it be used in the #if/#elif#else directives?

Upvotes: 0

Views: 4476

Answers (2)

zwol
zwol

Reputation: 140866

Only macros defined with #define will have their expected value in an #if. All other symbols (more precisely, all identifiers that remain on an #if line after macro expansion, except defined and, in C++, certain "alternative spellings" of arithmetic operators, such as and, or, bitand, bitor, and compl) are interpreted as having the value 0.

Upvotes: 2

Lily Ballard
Lily Ballard

Reputation: 185861

Sorry, you can't do this at all. Variables are not visible to the preprocessor. The preprocessor is at its heart a text manipulator. The only values it can see are ones defined with #define, not variables.

Upvotes: 12

Related Questions