It may have only been Visual C++ 6.0 or something, but I think I remember needing to add curly braces after a switch's case label to declare variables, is this still true with VS2010 and C++?

ex:

switch( 1 )
{
case 1:
{
  int a; //<-- ok
}
break;
case 2:
  int b; //<-- not ok?
break;
}

I only ask because I'm kind of under the weather and am in the middle of some updates to a project.

Dani AI

Generated

Short answer: you only need the extra { } when you want a new scope for declarations inside a case. In standard C++ a switch body is one block and case/default are just labels — they do not open a scope. That means a declaration with an initializer placed directly after a label can be ill-formed because control might "jump over" the initialization. To make a case-local variable safe and well-scoped, put the case body in braces.

A simple pattern that avoids the problem is to give each case its own block:

switch (value) {
case 1: {
    int local = compute(); // local to this case
    // use local
    break;
}
case 2: {
    std::string s("two");
    // use s
    break;
}
}

Since C++17 you also have an initializer in the switch header (e.g., switch (int v = f(); v)) if you need a value visible to the whole switch. If older compilers (VC6, etc.) behaved oddly, that matches your memory; modern compilers enforce the standard rules. If you see errors like "jump to case label" or "crosses initialization", the fix is to add braces or move the declaration outside the switch. See the standard wording and examples on the cppreference switch statement page.

Recommended Answers

All 2 Replies

No. You can declare variables in the main function.

int main() {

int a, b;


<rest of program here>

return 0;
}

Switch statement is a "flow of control" like the if-else statement, while loop, for statement, etc.

Also, with a switch statement. The code will continue to run until a break statement is found or until the end of the switch statement. You do not need additional brackets except the overall brackets that made the switch code block.

switch(c){    // beginning of switch code block

case 1: 
   dothisfunction();
   break;
case 2:
   dothatfunction();
   break;
default:
   cout <<"What are you doing?\n";
}      // end of switch code block
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.