-
January 19th, 2012, 05:32 PM
#1
switch with repeating cases?
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;
}
-
January 19th, 2012, 05:34 PM
#2
Re: switch with repeating cases?
Yes, that will work fine.
-
January 19th, 2012, 07:24 PM
#3
Re: switch with repeating cases?
-
January 19th, 2012, 08:13 PM
#4
Re: switch with repeating cases?
Originally Posted by acppdummy
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;
}
Code:
void foo()
{
int mycase = 0;
switch(mycase)
{
case 0:
break;
case 1:
case 2:
{
}
break;
case 2:
{
}
break;
}
}
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
Regards,
Paul McKenzie
-
January 19th, 2012, 09:56 PM
#5
Re: switch with repeating cases?
Well g++ didn't like it either:
error: duplicate case value
I suppose I could break it up by inserting some more switches like this?
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;
}
Or is there a way to turn off the "strict" mode in g++?
-
January 19th, 2012, 10:24 PM
#6
Re: switch with repeating cases?
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;
}
-
January 19th, 2012, 11:35 PM
#7
Re: switch with repeating cases?
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;
}
Last edited by nuzzle; January 19th, 2012 at 11:54 PM.
-
January 20th, 2012, 06:55 AM
#8
Re: switch with repeating cases?
-
January 20th, 2012, 07:29 AM
#9
Re: switch with repeating cases?
I missed that case 2 was in there twice, sorry.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|