Hi, Neil Heller!
On 23 Aug 97 10:59:00 you wrote to All
NH> I always thought that one of the features of C++ is that variables
NH> can be declared ANYWHERE (such as near where you're going to use them).
That's close true.
NH> However I ran across a situation in MSVC 1.6 with a CPP module that
1.6? Do you really have that version? I thousght MS stopped the 16 bit
compiler line at 1.52.
NH> seems to contradict this. Can someone explain to me why?
NH> If I write a switch statement thusly, I get compiler errors:
Yes, you should get them.
NH> switch (foo) {
NH> case 1 :
NH> int bar = 2;
NH> break;
NH> case 2 :
NH> int bar = 3;
NH> break;
NH> }
You must get a "bar: redefinition" at line 6. You must not define two objects
with identical name to the same scope. And in the above example you did that.
This is the same as if in a C program you write
int main()
{
int i;
int i; // error here: i already defined
return 0;
}
NH> However, if I write the code this way there are no errors:
NH> switch (foo) {
NH> case 1 : {
NH> int bar = 2;
NH> break;
NH> }
NH> case 2 : {
NH> int bar = 3;
NH> break;
NH> }
NH> }
Here you scoped both "bar" variables. So they are tho distinct local
variables that disappear at the closing } together with their value.
NH> I was under the assumption that the braces weren't necessary in C++ as
NH> far as declaring variables is concerned. Why then do I need the
NH> braces? Do the added braces affect portability in any way?
Braces have nothing with portability. They define block of execution and also
controls lifetime and visibility of objects. Inserting them will in general
produce totally different code.
Paul
... SENILE.COM found . . . Out Of Memory . . .
--- OS/2 Warp
---------------
* Origin: The FlintStones' Cave in BedRock (2:371/20)
|