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

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;

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.

What are some interesting uses of 'switch' in C/C++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
The switch statement in C/C++ has an interesing feature that all subsequent blocks will be executed if a condition is met
For example,
int a = 2;
int b = a;
switch(b)
{
case 1:cout<<1;
case 2:cout<<2;
case 3:cout<<3;
case 4:cout<<4;
};
The above code will output 234 unless I put a break statement in case 2.
In 3 years(quite small,yeah) of my C/C++ programming experience, I have never encountered a problem where I had to use switch without putting break statments in every case. But judging by the fact that this feature has been stuck for so long, there might be some utility of it.
Question: What are some clever uses of switch statement as to utilize the above mentioned feature in C/C++?
Probably one of the most interesting use cases I have seen would be Duff's Device the case where you extend a scope within a switch over multiple cases which would look something like this:
void send( int *to, const int *from, int count)
{
int n = (count + 7) / 8;
switch(count % 8)
{
case 0: do { *to = *from++; // <- Scope start
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); // <- Scope end
}
}
This is usually used when you want to apply a similar action to a set of values. For instance, the following :
switch (event) {
case DEVICE_DISCONNECTED:
case CONNECTION_ERROR:
case CONNECTION_TIMEOUT:
transitionTo(disconnectedState);
break;
case CONNECTION_SUCCESS:
transitionTo(connectedState);
break;
}
is much more concise and readable in my opinion than :
switch (event) {
case DEVICE_DISCONNECTED:
transitionTo(disconnectedState);
break;
case CONNECTION_ERROR:
transitionTo(disconnectedState);
break;
case CONNECTION_TIMEOUT:
transitionTo(disconnectedState);
break;
// ...
}
In my current project, I have the following enumeration:
enum NodeType
{
SCALAR, COMPOSITE, ARRAY, RESTRICTED_ARRAY
};
Thus, quite a few node-processing routines use this pattern:
switch (nodeType)
{
case SCALAR:
processScalar();
break;
case COMPOSITE:
processComposite();
break;
case RESTRICTED_ARRAY:
if (!handleRestrictions())
return false;
// continue to next case
case ARRAY:
processArray();
break;
}
Note that it's almost necessary to always mark the lack-of-break as explicitly intended with a comment (like I did above) - future maintainers (including yourself in 3 months) will thank you.
I've often used a construct to parse command line arguments like this:
switch (argument) {
case arg_h:
case arg__help:
case arg_questionmark:
printf("Help\n");
break;
case arg_f:
case arg__file:
//...
}
where argument is an enum type.

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.

Land mine game using only switch statement ...error occuring,,,,?

Look at this ...
https://www.youtube.com/watch?v=b7PD5969hho
( it's a helium ion :P( strangely enough) I need suggestions about how to incorporate 2 electrons without making the code hyper long)
I want the dots to be removed as well.
http://www.2shared.com/document/RbqXfIdH/Helium_ion_XD.html (this is my c++ code)
The code below also has a problem... I'm having problems with switch statement
#include<iostream>
#include<cmath>
#include<string>
#include<iomanip>
using namespace std;
#include <stdlib.h>
int main ()
{
int i=1,t=0,live=3;
char choice=' ';
char b1='a';
char b2='b';
char b3='c';
char b4='d';
char b5='e';
char b6='f';
char b7='g';
char b8='h';
char b9='i';
char b10='j';
clear:
switch (choice)
case 'a':
b1='*';
live--;
break;
case 'b':
b2='-';
t++;
break;
case 'c':
b3='*';
live--;
break;
case 'd':
b4='-';t++;
break;
case 'e':
b5='-';t++;
break;
case 'f':
b6='-';t++;
break;
case 'g':
b7='-';t++;
break;
case 'h':
b8='*';
live--;
break;
case 'i':
b9='-';t++;
break;
case 'j':
b10='-';t++;
break;
///////////////////////////BOX////////…
cout<<setw(20)<<'|'<<setw(10)<<'|'<<se…
cout<<setw(15)<<b1<<setw(5)<<'|'<<setw(5…
cout<<setw(20)<<'|'<<setw(10)<<'|'<<setw…
cout<<setw(20)<<'|'<<setw(10)<<'|'<<setw…
cout<<setw(60)<<"---------------------…
//////////////////////////////////////…
cout<<setw(20)<<'|'<<setw(10)<<'|'<<se…
cout<<setw(15)<<b6<<setw(5)<<'|'<<setw(5…
cout<<setw(20)<<'|'<<setw(10)<<'|'<<setw…
cout<<setw(20)<<'|'<<setw(10)<<'|'<<setw…
cout<<setw(60)<<"---------------------…
/////////////////////////////////box end/////////////////////////////////////…
//////////////start////////////////
cout<<setw(40)<<"THIS GRID CONTAINS 8 BOMBS...CHOOSE 15 NUMBERS WITHOUT hittng a landmine";
{
cout<<"YOUR "<<live <<"LIVES REMAIN"<<endl;
cout<<"ENTER YOUR"<< i << "NUMBER :";
i++;
cin>>choice;
if(t==15)
{
cout<<"YOU WIN";
goto end;
};
if(live==0)
cout<<"YOU LOSE";
goto clear;};
if(live==0)
cout<<"YOU LOSE";
end:
return 0;
}
My first impressions from the video you supplied is that you need some form of simple graphics library to output what you're trying to do. Outputting "pseudo-graphics" within a console is just going to get increasingly messy and confusing to manage. Look into SDL, for instance.
To address the second section of your question, for one, your switch statement needs curly brackets to encapsulate its body. Indentation and formatting practices will help you identify these issues quickly and independently, so it would be a good idea to get into a habit of using these.
As a side note, I'd suggest you avoid using goto statements in your code, they quickly become unmanageable when a project grows. Maybe it would be a good idea to revise your C/C++.

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;