Variable Scope in C++?

前端 未结 4 1345
半阙折子戏
半阙折子戏 2021-01-27 14:52

In c++, any variables declared in main will be available throughout main right? I mean if the variables were declared in a try loop, will they would still be accessible througho

相关标签:
4条回答
  • 2021-01-27 15:15

    Local variables in C++ have block scope, not function scope. The variable number is only in scope inside the try block.

    To make this work, you have (at least) two choices:

    1. Make the variable accessible at function scope (not so good):

      int main() {
          int number;
          try {
              number = <some possibly-exception-throwing call>;
          } catch (...) {
              cout << "Error\n";
              return 0;
          }
          ++number;
          cout << number;
      }
      
    2. Place all use of the variable inside the try scope (much better):

      int main() {
          try {
              int number = <some possibly-exception-throwing call>;
              ++number;
              cout << number;
          } catch (...) {
              cout << "Error\n";
          }
      }
      

    I strongly favour the second choice, for a few reasons:

    1. You don't have to explicitly handle the case that the variable wasn't initialised correctly.
    2. There's no risk of accidentally using the uninitialised variable. In fact, your code would exhibit precisely this bug if C++ locals had function scope (assuming the intent was to initialise number with something more interesting than a constant).
    3. It keeps declaration and initialisation together.

    Appendix: For main() in particular, there's a third choice:

        int main() try {
            ...
        } catch {
            cout << "Error\n";
        }
    

    This wraps the entire program, including static initialisers outside of main() proper, in a try...catch.

    0 讨论(0)
  • 2021-01-27 15:15

    That's normal; each { ... } block mark a new scope, and variables declared inside it are local to it. If you want number to be available throughout all main declare it outside the try block.

    0 讨论(0)
  • 2021-01-27 15:33

    In c++, any variables declared in main will be available throughout main right?

    No!

    The scope of every variable is the block where the variable defined and its nested blocks : {}

    You must put int number; outside the try{} block.


    More on here:

    Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int.

    A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.

    enter image description here

    Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.

    The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa.

    0 讨论(0)
  • 2021-01-27 15:37

    The scope of number is limited to the try block. Pull out this declaration to the main scope to access the variable after the try block:

    int main()
    {
       int number = 0;
       try 
       {
         // do something...
       }
    
       catch (...)
       {
         cout <<"Error";
       }
    
       number ++;
       cout <<number;
    
       return 0;
    }
    
    0 讨论(0)
提交回复
热议问题