0

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?

3
  • 8
    Preprocessor directives and variables are completely different. You can't do this, at all. Commented Jan 19, 2013 at 19:57
  • The preprocessor doesn't understand C++! It has its own interpretation. Commented Jan 19, 2013 at 20:28
  • Only #define symbols work in #if Commented Jan 19, 2013 at 21:16

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i used to think that const can be used as a replacement for #define for example, #define TEST 1 or const int TEST = 1, can we use these as #if TEST == 1 .... #endif
No. You can only use a const instead of a #define if you don't need to use the constant in #if. Often this is fine. Other times all you care about in #if is whether or not the constant has some value, so for instance you may see #define EPERM EPERM in <errno.h> and the numeric value is set with an enum. That lets you do #ifdef EPERM or #if defined EPERM but not #if EPERM == 23.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.