Variable Scope in C++?

前端 未结 4 1400
半阙折子戏
半阙折子戏 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 = ;
          } 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 = ;
              ++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.

提交回复
热议问题