Re: compilation error in switch case in c++
On Feb 6, 2:07 pm, Pete Becker <p...@versatilecoding.com> wrote:
> On 2008-02-06 04:15:14 -0500, Rahul <sam_...@yahoo.co.in> said:
> > class A
> > {
> > int i;
> > };
> > int main()
> > {
> > switch(1)
> > {
> > case 1 :
> > // {
> > A obj;
> > printf("case 1\n");
> > // }
> > break;
> > case 2 :
> > A obj1;
> > printf("case 2\n");
> > break;
> > }
> > }
> This is illegal. When should obj's destructor be run?
When you leave scope. There's no problem with the destructor
(formally, at least); you're allowed to jump out of scope, and
it's up to the compiler to call any destructors. (And of
course, the semantics of switch/break are those of goto.)
The problem is rather when will the initialization occur. In
the above example, without the {}, obj is in scope, visible and
usable in case 2. The code jumps over an initialization. (And
I don't think that this exact example is illegal---class A
doesn't have any initialization. But it would be illegal if
class A had a non-trivial constructor, or if obj had any
initialization expression.)
The reason why the declaration of obj1 is legal, of course, is
that there isn't any label after it. It is the label ("case
2:") after the declaration which causes the code to be illegal.
Of course, the reason why you're not allowed to jump over
non-trivial initialization is because doing anything with the
object afterwards is very problematic. And in C++, you will do
something with the object when it goes out of scope: call the
destructor. (Presumably, if the object has trivial
initialization, the destructor knows how to cope with it, and
calling the destructor without having done the initialization is
OK. In practice, I don't think I've ever seen an object with a
non-trivial destructor which didn't have non-trivial
constructors as well.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
|