Switch Statement continue - c++

Is the following possible in C++?
switch (value) {
case 0:
// code statements
break;
case 1:
case 2:
// code statements for case 1 and case 2
/**insert statement other than break here
that makes the switch statement continue
evaluating case statements rather than
exit the switch**/
case 2:
// code statements specific for case 2
break;
}
I want to know if there is a way to make the switch statement continue evaluating the rest of the cases even after it has hit a matching case. (such as a continue statement in other languages)

How about a simple if?
switch (value)
{
case 0:
// ...
break;
case 1:
case 2:
// common code
if (value == 2)
{
// code specific to "2"
}
break;
case 3:
// ...
}

Once the case label is decided, there is no way to have the switch continue to search for other matching labels. You can continue to process the code for the following label(s) but this doesn't distinguish between the different reasons why a case label was reached. So, no, there is no way to coninue the selection. In fact, duplicate case labels are prohibited in C++.

Yep, just don't put in a break. It will naturally fall down to the other switch statements.

Related

How do if/else work intermixed with switch/case interact? [duplicate]

Reviewing some 3rd party C code I came across something like:
switch (state) {
case 0:
if (c=='A') { // open brace
// code...
break; // brace not closed!
case 1:
// code...
break;
} // close brace!
case 2:
// code...
break;
}
Which in the code I was reviewing appeared to be just a typo but I was surprised that it compiled with out error.
Why is this valid C?
What is the effect on the execution of this code compared to closing the brace at the expected place?
Is there any case where this could be of use?
Edit: In the example I looked at all breaks were present (as above) - but answer could also include behaviour if break absent in case 0 or 1.
Not only is it valid, similar structure has been used in real code, e.g., Duff's Device, which is an unrolled loop for copying a buffer:
send(to, from, count)
register short *to, *from;
register count;
{
register n = (count + 7) / 8;
switch(count % 8) {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while(--n > 0);
}
}
Since a switch statement really just computes an address and jumps to it, it's easy to see why it can overlap with other control structures; the lines within other control structures have addresses that can be jump targets, too!
In the case you presented, imagine if there were no switch or breaks in your code. When you've finished executing the then portion of a if statement, you just keep going, so you'd fall through into the case 2:. Now, since you have the switch and break, it matters what break can break out of. According to the MSDN page, “The C break statement”,
The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement.
Since the nearest enclosing do, for, switch, or while statement is your switch (notice that if is not included in that list), then if you're inside the then block, you transfer to the outside of the switch statement. What's a bit more interesting, though, is what happens if you enter case 0, but c == 'A' is false. Then the if transfers control to just after the closing brace of the then block, and you start executing the code in case 2.
In C and C++ it is legal to jump into loops and if blocks so long as you don't jump over any variable declarations. You can check this answer for an example using goto, but I don't see why the same ideas wouldn't apply to switch blocks.
The semantics are different than if the } was above case 1 as you would expect.
This code actually says if state == 0 and c != 'A' then go to case 2 since that's where the closing brace of the if statement is. It then processes that code and hits the break statement at the end of the case 2 code.

Why can this if statement overlap a case block in a switch statement? [duplicate]

Reviewing some 3rd party C code I came across something like:
switch (state) {
case 0:
if (c=='A') { // open brace
// code...
break; // brace not closed!
case 1:
// code...
break;
} // close brace!
case 2:
// code...
break;
}
Which in the code I was reviewing appeared to be just a typo but I was surprised that it compiled with out error.
Why is this valid C?
What is the effect on the execution of this code compared to closing the brace at the expected place?
Is there any case where this could be of use?
Edit: In the example I looked at all breaks were present (as above) - but answer could also include behaviour if break absent in case 0 or 1.
Not only is it valid, similar structure has been used in real code, e.g., Duff's Device, which is an unrolled loop for copying a buffer:
send(to, from, count)
register short *to, *from;
register count;
{
register n = (count + 7) / 8;
switch(count % 8) {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while(--n > 0);
}
}
Since a switch statement really just computes an address and jumps to it, it's easy to see why it can overlap with other control structures; the lines within other control structures have addresses that can be jump targets, too!
In the case you presented, imagine if there were no switch or breaks in your code. When you've finished executing the then portion of a if statement, you just keep going, so you'd fall through into the case 2:. Now, since you have the switch and break, it matters what break can break out of. According to the MSDN page, “The C break statement”,
The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement.
Since the nearest enclosing do, for, switch, or while statement is your switch (notice that if is not included in that list), then if you're inside the then block, you transfer to the outside of the switch statement. What's a bit more interesting, though, is what happens if you enter case 0, but c == 'A' is false. Then the if transfers control to just after the closing brace of the then block, and you start executing the code in case 2.
In C and C++ it is legal to jump into loops and if blocks so long as you don't jump over any variable declarations. You can check this answer for an example using goto, but I don't see why the same ideas wouldn't apply to switch blocks.
The semantics are different than if the } was above case 1 as you would expect.
This code actually says if state == 0 and c != 'A' then go to case 2 since that's where the closing brace of the if statement is. It then processes that code and hits the break statement at the end of the case 2 code.

Clang-Format: how to get one-line case statements in a switch statement

Is it possible to obtain switch statements formatted as:
switch (index) {
case 0: /* statement */ break;
case 1: /* statement */ break;
default: break;
}
with Clang-Format?
Yes, you need to set AllowShortCaseLabelsOnASingleLine to true. You can experiment in real-time with your .clang-format configuration on this great website: "clang-format-configurator".

Using a switch in a do..while loop, in C++

A simple programm that reads strings, and responds using a switch;
in this do-while loop containing a switch, I am able to run case 1-4 with no issues, but once i hit the default case, the programme simply loops the default case over and over again the code is as follows;
do { switch ( switchstring (entry, input) )
/*the switchstring function is one 1 wrote to convert a given entry(string),
into an input(integer)*/
{
case 1:
//code
repeat = 2;
break;
case 2:
//code
repeat = 2;
break;
case 3:
//code
repeat = 2;
break;
case 4:
//code
repeat = 2;
break;
default:
//code
repeat = 1;
break;}} while(repeat == 1);
the 2nd question is regarding my switchstring() function; is there a way to change the switch function such that it reads;
case (insert string):
i.e. so that I can remove the entire switchstring() function
thanks in advance!
Show us how switchstring (entry, input) works.
The problem you are facing is because, in default you do the following:
repeat = 1;
Which makes while(repeat == 1) always true. And then switchstring (entry, input) always return something that makes your switch block always go the the default case again.
When no case will be true in switch, then it will go in default case of switch and you are specifying repeat=1; in default. After that while condition will be checked and it will be true because repeat is 1, again it will go to do and check condition, your switch function will return something and it will go to default.
To solve 2nd question regarding your switchstring() function, you have to show your code what you are doing in that function, So that i can give you best suggestion.

Switch statement using or

I'm creating a console app and using a switch statement to create a simple menu system. User input is in the form of a single character that displays on-screen as a capital letter. However, I do want the program to accept both lower- and upper-case characters.
I understand that switch statements are used to compare against constants, but is it possible to do something like the following?
switch(menuChoice) {
case ('q' || 'Q'):
//Some code
break;
case ('s' || 'S'):
//More code
break;
default:
break;
}
If this isn't possible, is there a workaround? I really don't want to repeat code.
This way:
switch(menuChoice) {
case 'q':
case 'Q':
//Some code
break;
case 's':
case 'S':
//More code
break;
default:
}
More on that topic:
http://en.wikipedia.org/wiki/Switch_statement#C.2C_C.2B.2B.2C_Java.2C_PHP.2C_ActionScript.2C_JavaScript
The generally accepted syntax for this is:
switch(menuChoice) {
case 'q':
case 'Q':
//Some code
break;
case 's':
case 'S':
//More code
break;
default:
break;
}
i.e.: Due the lack of a break, program execution cascades into the next block. This is often referred to as "fall through".
That said, you could of course simply normalise the case of the 'menuChoice' variable in this instance via toupper/tolower.
'q' || 'Q' results in bool type result (true) which is promoted to integral type used in switch condition (char) - giving the value 1. If compiler allowed same value (1) to be used in multiple labels, during execution of switch statement menuChoice would be compared to value of 1 in each case. If menuChoice had value 1 then code under the first case label would have been executed.
Therefore suggested answers here use character constant (which is of type char) as integral value in each case label.
Just use tolower(), here's my man:
SYNOPSIS
#include ctype.h
int toupper(int c);
int tolower(int c);
DESCRIPTION
toupper() converts the letter c to upper case, if possible.
tolower() converts the letter c to lower case, if possible.
If c is not an unsigned char value, or EOF, the behavior of these
functions is undefined.
RETURN VALUE
The value returned is that of the converted letter, or c if the
conversion was not possible.
So in your example you can switch() with:
switch(tolower(menuChoice)) {
case('q'):
// ...
break;
case('s'):
// ...
break;
}
Of course you can use both toupper() and tolower(), with capital and non-capital letters.
You could (and for reasons of redability, should) before entering switch statement use tolower fnc on your var.
switch (toupper(choice))
{
case 'Q':...
}
...or tolower.
if you do
case('s' || 'S'):
// some code
default:
// some code
both s and S will be ignored and the default code will run whenever you input these characters. So you could decide to use
case 's':
case 'S':
// some code
or
switch(toupper(choice){
case 'S':
// some code.
toupper will need you to include ctype.h.