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 = ;
} 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 = ;
++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.