I have some cases in a switch statement sharing common code. Would this work?
Code:switch(mycase){
case 0: { code for case 0; } break;
case 1:
case 2: {
common code for case 1 and 2;
}
break;
case 2: {
code only for case 2;
}
break;
}
Printable View
I have some cases in a switch statement sharing common code. Would this work?
Code:switch(mycase){
case 0: { code for case 0; } break;
case 1:
case 2: {
common code for case 1 and 2;
}
break;
case 2: {
code only for case 2;
}
break;
}
Yes, that will work fine.
Thank you!
Code:void foo()
{
int mycase = 0;
switch(mycase)
{
case 0:
break;
case 1:
case 2:
{
}
break;
case 2:
{
}
break;
}
}
Regards,Quote:
Thank you for testing your code with Comeau C/C++!
Tell others about http://www.comeaucomputing.com/tryitout !
Your Comeau C/C++ test results are as follows:
Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing. All rights reserved.
MODE:strict errors C++ C++0x_extensions
"ComeauTest.c", line 13: error: case label value has already appeared in this
switch at line 9
case 2:
^
1 error detected in the compilation of "ComeauTest.c".
In strict mode, with -tused, Compile failed
Paul McKenzie
Well g++ didn't like it either:
I suppose I could break it up by inserting some more switches like this?Quote:
error: duplicate case value
Or is there a way to turn off the "strict" mode in g++?Code:switch(mycase){
case 0: { code for case 0; } break;
case 1:
case 2: {
common code for case 1 and 2;
}
break;
}
switch(mycase){
case 2: {
code only for case 2;
}
break;
}
I wonder if it would not just be simpler to write:
Code:switch(mycase){
case 0: { /* code for case 0; */ } break;
case 1:
case 2: {
/* common code for case 1 and 2; */
if (mycase == 2) {
/* code only for case 2; */
}
}
break;
}
I would prefer to first separate the cases and then use functions for common code, like
Code:switch (mycase){
case 0:
// specific to case 0
break;
case 1:
do12(); // common to both 1 and 2
// specific to case 1
break;
case 2: {
do12(); // common to both 1 and 2
// specific to case 2
break;
}
Thanks everyone!
I missed that case 2 was in there twice, sorry.