C++ , Switch case in a switch case - c++

Is it possible to have a switch case in a switch case 3 times? So if I have the main switch case and three in it, like:
switch(bla)
case 1:
switch(bla2)
bla
break;
case 2:
switch(bla2)
bla
break
case 3:
switch(bla2)
bla
break
So bla 2is the same string that I´m checking on.

Yes, you may nest switch statements.
Unlike in your example, you would have to make proper use of braces ({}) so that it is clear to the computer what you want to do. I suppose you'd have to actually decide what you want to do, first.

Yes, Nested switches are possible. However you must use "{}".
switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ... }
Check this out : http://www.tutorialspoint.com/cplusplus/cpp_nested_switch.htm

Related

Error: break statement not within loop or switch

I wrote this part of code and a series of error are being shown. The above mentioned error being the first. What is wrong in the code?
void direction(char ch)
{
switch(ch)
case 'w': if(dirn!=3){dirn=1;}
break;
case 'a': if(dirn!=2){dirn=4;}
break;
case 's': if(dirn!=1){dirn=3;}
break;
case 'd': if(dirn!=4){dirn=2;}
break;
You can choose to omit the opening and closing braces for a switch statement only when you have only one case in your switch block as shown below:
void direction(char ch)
{
switch(ch)
case 'w': if(dirn!=3){dirn=1;}
}
But, if you have got multiple cases to deal with like in your case then you must enclose them inside a pair of opening and closing braces to create a code block for the switch statement as shown below:
void direction(char ch)
{
switch(ch)
{//opening brace for starting of statement block
case 'w': if(dirn!=3){dirn=1;}
break;
case 'a': if(dirn!=2){dirn=4;}
break;
case 's': if(dirn!=1){dirn=3;}
break;
case 'd': if(dirn!=4){dirn=2;}
break;
}//closing brace for closing of statement block
So you will have to either remove all the cases but one OR add the pair of braces to create statement block. In all other cases your code won't compile successfully.
You have forgotten the switch braces :
void direction(char ch)
{
switch(ch)
{
case 'w': if(dirn!=3){dirn=1;}
break;
case 'a': if(dirn!=2){dirn=4;}
break;
case 's': if(dirn!=1){dirn=3;}
break;
case 'd': if(dirn!=4){dirn=2;}
break;
}
}
switch statement requires braces block, where all labels including default one should be:
switch(ch)
{
case 'w': if(dirn!=3) dirn=1;
break;
case 'a': if(dirn!=2) dirn=4;
break;
case 's': if(dirn!=1) dirn=3;
break;
case 'd': if(dirn!=4) dirn=2;
break;
default:
break;
}
The statement after switch must be a compound statement to contain case, default and break. Break got a special meaning here, different from loops. If brace was omitted only next line after switch is part of its statement.

Why is "defau4t" legal in a switch statement? [duplicate]

This question already has answers here:
Default case in a switch condition
(3 answers)
Closed 8 years ago.
I came up with this program in some other site and thought of trying it, here's the program:
#include <stdio.h>
int main()
{
int a=10;
switch(a)
{
case '1': printf("one");
break;
case '2': printf("two");
break;
defau4t: printf("none");
}
return 0;
}
Suprisingly enough, this compiles without errors or warnings. How is this possible? Isn't there an error on keyword "default"?
Could anyone explain this behaviour?
The token is not considered to be a keyword at all. This is a goto jump mark named "defau4t" pointing at otherwise dead code (after the break; of case '2':)...
Try this for laughs (and an endless loop):
switch(a)
{
case '1': printf("one");
break;
case '2': printf("two");
break;
defau4t: printf("none");
default: goto defau4t;
}
One flaw with the switch statement is that you can wildly jump in and out of them using goto. At any point inside the switch (or outside it for that matter), you can place a label, that you can jump to with goto. Of course, that is very bad practice as it leads to spaghetti code.
So defau4t: is merely a label, and labels can be placed pretty much anywhere inside function bodies.
Apart from that typo of default.
i think you need to also update
case '1': printf("one");
break;
case '2': printf("two");
break;
to
case 1: printf("one");
break;
case 2: printf("two");
break;

Switch Statement continue

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.

c++ classes switch case

switch(choice)
{
case 1:
uinstance1.addNewProduct(data);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
uinstance1.listAllProducts(data);
break;
case 8:
break;
case 9:
break;
case 10:
//name,category,barcode,price,manufacturer,noinstock,soldpermonth,expirydate,discount
// Perishable(string,string,string,double,string,int,int);
Perishable item0("Ferrari","Automobile","9999",2999.99,"Popular",5,0);
data.addNew(item0);
break;
default:
cout<<"Wrong Choice "<<endl;
system("pause");
break;
}
}
Hi ,i have been thinking about this error for quite some time and cant seem to figure out the issue.
error C2361: initialization of 'item0' is skipped by 'default' label
: see declaration of 'item0'
Some help would be appreciated.
Thanks
The whole select block counts as one scope, if you decalare a variable in that scope you need to initialize it in every case statement (every possible execution path). You can avoid it by creating a additional scope in your case to avoid the problem (see the brackets):
switch(choice)
{
case 1:
uinstance1.addNewProduct(data);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
uinstance1.listAllProducts(data);
break;
case 8:
break;
case 9:
break;
case 10:
{
//name,category,barcode,price,manufacturer,noinstock,soldpermonth,expirydate,discount
// Perishable(string,string,string,double,string,int,int);
Perishable item0("Ferrari","Automobile","9999",2999.99,"Popular",5,0);
data.addNew(item0);
}
break;
default:
cout<<"Wrong Choice "<<endl;
system("pause");
break;
}
}
MSDN explains the error C2361 aptly:
The initialization of identifier can be skipped in a switch statement. You cannot jump past a declaration with an initializer unless the declaration is enclosed in a block. (Unless it is declared within a block, the variable is within scope until the end of the switch statement.)
Always pay attention to the error numbers they provide vital information about why the error.
You forgot the braces in one of the cases.
case 10:
{
^^^
Perishable item0;
data.addNew(item0);
break;
}
^^^
Your label is crossing initialization which is illegal. Pretty sure moving default to the top should fix it. You can also add code blocks { } around your relevant code. If you still have problems then move your object outside of the switch block.
You can't create variables inside case statements if you don't define explicity the scope.
There is another discussion about that: Variables inside case statement
case 10:
{ // <<-- This gives explicit scope for the stack variable and let's you get rid of the error
Perishable item0;
// ...
}
break;

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.