On (23 Aug 97) Neil Heller wrote to All...
NH> I always thought that one of the features of C++ is that variables can
NH> be declared ANYWHERE (such as near where you're going to use them).
That's pretty nearly true, but not quite...
NH> However I ran across a situation in MSVC 1.6 with a CPP module that
NH> seems to contradict this. Can someone explain to me why?
MSVC 1.6? I assume that was a typo and you meant 1.5?
NH> If I write a switch statement thusly, I get compiler errors:
NH> switch (foo) {
NH> case 1 :
NH> int bar = 2;
NH> break;
NH> case 2 :
NH> int bar = 3;
NH> break;
NH> }
Yup, you should. When/if you jump past initialization of a variable,
you should get an error. You've also defined the same variable twice
in the same scope, which is an error as well.
There was a lot of debate as to what the "right thing" to do was when
you jumped past the initialization of a variable. One camp said that
initialization was part of creating the variable, so the initialization
had to take place. The other camp said that you were jumping past the
code, so the code to initialize the variable shouldn't execute.
Eventually both camps agreed that no matter which way you went, you had
a problem, and they made the whole thing illegal.
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're doing two things. First of all, with the braces present,
you've got two separate variables that both happen to be named `bar',
but which are in separate scopes, so that's reasoanble. Second, when
the switch statement jumps to label 2, the initialization of the first
bar isn't an issue - the scope it's in is never entered, so it's clear
that it should never be created or initialized.
This isn't nearly as difficult to handle with variables of type int, but
consider the following:
class number {
int a_number;
public:
operator int() {
return a_number;
}
number(int init) { cout << init << endl; }
~number(int init) { cout << "number dies" << endl; }
};
switch (foo) {
case 1:
number x(3);
break;
case 2:
cout << int(x) << end;
break;
}
Now what should happen when foo==2? Should the ctor for `x' run twice
with two different values? If we just used `x' in the second case
instead of defining it, should we be able to depend upon it having been
initialized to 3? Ultimately, it was decided that it was best to just
make the whole thing illegal.
Later,
Jerry.
... The Universe is a figment of its own imagination.
--- PPoint 1.90
---------------
* Origin: Point Pointedly Pointless (1:128/166.5)
|