Here's a larger example to look at:
-------------------source---------------
#include <iostream>
#include <stdlib.h>
using namespace std;
int x = 1;
void printX ()
{
cout << "Global x = " << x;
}
int main()
{
cout << "Global x = " << x << endl;
int x = 2;
cout << "In main x = " << x << endl;
if( true )
{
int x = 3;
cout << "In condition x = " << x << endl;
}
cout << "In main x = " << x << endl;
atexit( printX );
}
-------------------/source---------------
-------------------output----------------
Global x = 1
In main x = 2
In condition x = 3
In main x = 2
Global x = 1
------------------/output----------------
Nested variable declarations was a term I'd never heard before, so I
googled it. First for C++. I got absolutely no worth-my-time findings,
so I'm thinking that C++ doesn't sup****t them. Or maybe, I still don't
understand the term, but either way...
C++, in my example, created a variable in global scope, that I
printed. When I declared another variable of the same name, C++ simply
decided that it's scope was local and local variables trump globals.
So when I printed the second time, it printed the local variable.
You might already know this, but I need to make sure we're speaking on
the same level, seeing as we're speaking with different terms.
This feature can really help you not make an idiot of yourself, some
might say, when you declare things locally. If I include a file that
uses a global variable, and I make a variable of the same name and use
it locally, I can do so because mine has a local scope and the
compiler won't get confused when I call the included file's functions.
There are millions of examples along those lines.
But, a lot of coders will say that it's a bad programming practice to
have two variables of the same name. C++ would crash with a multiple
definitions rule when you did this, and force you to rename it.
I don't think it's good or bad, but this is what a language is: A
philosophy on what practices should be forced, which should be
encouraged, and which are to be optional.
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|