views:

106

answers:

2

hello, i use visual studi 2008. (c++)

in my switch case a wanted to create an object, but i doens't work.

is it right, that i can't create an object in a switch case?

if that's right,whats the best way to work around it,

a new method that's creates that object?

edit the code:

switch (causwahl){
case '1':
cAccount *oAccount = new cAccount (ID);

case '2' ....
+6  A: 

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

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

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

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

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

case 2:
  {
    MyObject bar;
    // ...
    break;
  }
}
Peter Alexander
+1 Um, i messed up my answer. Liking yours better :)
Johannes Schaub - litb
+1  A: 

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

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

There is nothing wrong with if-elses.

Tronic
+1 for for not having default-label in switch statements.
ArunSaha