Object creation inside swtich statements

Is it not possible to create an object inside a case of a switch statement? I tried and got the error:

error C2360: initialization of 'account' is skipped by 'case' label
Last edited on
Reduce the scope of the new object using braces:
1
2
3
4
5
6
7
8
9
switch ( something )
{
     case foo:
          int x; // error
     case bar:
     {
          int y; // OK: the scope of y is limited by the braces
     }
}
Thank you :) ... is this going to cause prolems later on though if I start executing statements that are outside of the switch statement? I Don't think I will need to but for future reference.
I don't think you would have problems but what you exactly mean with "start executing statements that are outside of the switch statement" ?
1
2
3
4
5
6
7
8
9
10
11
int main()
{
     switch ( something )
     {
          case bar:
          {
               int y; // OK: the scope of y is limited by the braces
          }
     }

     .. //start using object here 
if by the object you mean the defined int, yes. It doesn't exist outside of its scope.
1
2
3
4
5
6
7
8
9
switch(foo)
{
  case bar:
  {
    int y;
  }
}

y = 5;  // ERROR 

1
2
3
4
5
6
7
8
9
int y;
switch(foo)
{
  case bar:
  {
  }
}

y = 5;  // OK 
@Disch... the only problem I have with that is that the input i get from the user is attained from within the switch and is needed when initializing the object (for the constructor). I could do it how you have done it but it would make the code a bit messy...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
MyObj* obj = 0;

switch(foo)
{
case bar:
  obj = new MyObj( stuff, morestuff );
  break;
}

if(obj)
{
  // do stuff
  delete obj;
}


EDIT:
or, if reassignment isn't a problem:

1
2
3
4
5
6
7
8
9
10
MyObj obj;

switch(foo)
{
case bar:
  obj = MyObj( stuff, morestuff );
  break;
}

// do stuff 
Last edited on
Topic archived. No new replies allowed.