Using variables in the preprocessor directives

一世执手 提交于 2019-12-13 06:31:05

问题


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?


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/14418258/using-variables-in-the-preprocessor-directives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!