简体   繁体   English

有没有办法检查在编译时是否声明了变量?

[英]is there a way to check if variable is declared at compile time?

I mean case like this (this is of course false code /idea only/ as I know it doesn't work like that): 我的意思是这样的情况(这当然是错误的代码/ idea only /,据我所知它不会那样工作):

int main() {
  int my_int = 42;
  #ifdef my_int
    my_int = 43;
  #else
    int my_int = 43;
}

I know that c/c++ program cannot see the names of the variables and cannot tell if it was set or not but compiler can do it, and I ask here is there any way to direct compiler to a given action like omitting or inserting a snippet of code when it encounters a situation when there are duplicate declarations in the same block. 我知道c / c ++程序看不到变量名,也无法告诉它是否已设置,但是编译器可以做到,我问这里有什么方法可以将编译器定向到给定的操作,例如省略或插入代码段代码遇到相同块中有重复声明的情况。

No. The only thing that can happen when you have duplicate declarations, is a compiler error. 不。当您有重复的声明时,唯一可能发生的是编译器错误。 It's always ill-formed. 它总是格式错误。 And because the pre-processor has no knowledge of variables, you can't use that either. 而且由于预处理器不了解变量,因此您也不能使用它。

No, there is no way. 不,没有办法。 And even if there were, using it would go down the path towards madness. 即使有,使用它也会走上疯狂的道路。

If you know that the declaration of a symbol is conditional on some defined constant, use an #ifdef on that constant to decide what to do. 如果您知道符号的声明以某个定义的常量为条件,请对该常量使用#ifdef来决定要做什么。

If you don't know what the declaration of a symbol is conditional on, you really should not be messing around with that symbol because obviously it's external to your project. 如果您不知道符号的声明是基于什么条件的,那么您真的不应该搞混该符号,因为它显然在您的项目外部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM