Johnny, read my post again, you cant do that, the variable is GUARANTEED to exist.
compiled code creates variables at compile time.
in c++ when you say "if (not x)" you are saying "if (x==false)"
if x didn't exist, your code "if(not x)" would not compile so would be impossible to run.
this is because c++ is converted to machine code before it is run so everything has to exist already so the conversion (compilation) works.
interpreted languages like php and lua don't work like that, they generate code as they need to, JIT compiled (just in time) so you will often need to check if a variable has been created yet.
this is one of the fundamental differences between compiled languages and interpreted languages.
if your example, the int x will create the variable at function scope, but in c++ it will only exist in the braces that it was declared in, scoping is much tighter in C++.
the following code creates 4 variables all called x, each exists only within the braces it was declared in except x=1 which is global.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int x=1;
void myFunc()
{
int x=2;
cout << x; // outputs 2
{
int x=3;
cout << x; // outputs 3
{
int x = 4;
cout << x; // outputs 4
}
cout << x; // outputs 3
}
cout << x; // outputs 2
}
|