[ACCEPTED]-create an object in switch-case-switch-statement

Accepted answer
Score: 12

I can't say for sure with such a vague question, but 5 I'm guessing that you're doing something 4 like this:

switch(foo)
{
case 1:
  MyObject bar;
  // ...
  break;

case 2:
  MyObject bar;
  // ...
  break;
}

This isn't allowed because each 3 case statement has the same scope. You need 2 to provide more scope if you want to use 1 the same variable name:

switch(foo)
{
case 1:
  {
    MyObject bar;
    // ...
    break;
  }

case 2:
  {
    MyObject bar;
    // ...
    break;
  }
}
Score: 1

I suggest avoiding switch-case because of 16 this and other problems. You can allow variable 15 definitions by extra curly braces, but that 14 looks messy and causes two levels of indentation. Other 13 problems are that you can only use integer/enum 12 values for cases, that the break statement cannot 11 be used to break from a loop outside the 10 switch. Forgetting to break is also a very 9 common programming mistake that cannot be 8 detected by the compiler (because it is 7 still valid code) and it leads to hard to 6 debug bugs.

Personally I only use switch-case 5 with enum values, and even then never with 4 a default label. This has the benefit of 3 getting me a compile warning (from GCC) if 2 not all possible values of the enum are 1 handled.

There is nothing wrong with if-elses.

Score: 0
switch (choice)
    {
    case 1:
        {
            cout<<"\nBike object created********"<<endl;
            Bike B1(2,4,50);
            V=&B1;
            V->Display_Details();

            V->CallToll(persons);
           break;
      }

    case 2:
       {  
            cout<<"\n CAR object created********"<<endl;
            Car C1(4,8,50);
            V=&C1;
            V->Display_Details();
            V->CallToll(persons);

         break;

       }
     default:
           cout<<"You have entered an invalid choice...........Please Enter valid choice........"<<endl;


    }

  

0

More Related questions