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.

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.