简体   繁体   中英

how to check whether the variable is in scope or not in C++

I need to check if a variable "var1" is present in the current scope or not.

somefunction()
{

     ...
     ....
     {
          ......
          string var1("");
          ...
          // if i check var1..it should be in scope
          // something like inScope(var1)..return true if it is in scope else false
     }
     // if i check var1..it should be out of scope
     // something like inScope(var1)..return true if it is in scope else false
}

I believe you've misunderstood something at the very core of the language, or the toolchain.. Methods, classes, variables etc - they either 'exist' and 'are in scope' or not. If you try to actually use anything that "is not in the scope", this is a hard error and attempt to compile such code will usually just break. There is very little point in checking and branching the logic depending on existence of local variables.. I really think that you have overcomplicated something. If in the "later code" of your method you just want to check if something has happened earlier - why don't you create simple bool variable at the beginning of the method, initialize it to false , and set it to true only if the thing happened? and later just check the variable?

Having said that, while it is not possible to check whether a local variable is defined or not, it is completely possible to check whether a class member exists or not - due to some smart tricks with templates and SFINAE. I mean - you can test whether a class X defines a field Y or a method Z and statically get a true/false response at compilation time.

you may want to check for example: https://stackoverflow.com/a/7687190/717732 or https://stackoverflow.com/a/2133273/717732

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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