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
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:
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;
}
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:
number
with something more interesting than a constant).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.
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.
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.
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.
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;
}