Switch case "appears" to not be working C++ [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Essentially my switch case is not working properly in that statements for conditions I don't think are met, are executing anyway.
Example input:
CerseiTyrion
Expected output:
Cersei
Tyrion
Actual output:
Cersei
Tyrion
Jon
Dany
Tyrion
Jon
Dany
The goal of the following function is to parse some input text for an adventure game, and let the game know about some of the important information contained within the text. It then continues to use what it finds to execute code that should always run with the rest of the function if certain conditions are met.
Minimal, complete; verifiable example:
void HandleGameState( const std::string& text ) {
enum Characters {
Cersei = 0x01,
Tyrion = 0x02,
Jon = 0x04,
Dany = 0x08
};
unsigned int mask = 1;
switch( characterMask & mask )
{
case Cersei:
{
std::cout << "Cersei" << std::endl;
};
case Tyrion:
{
std::cout << "Tyrion" << std::endl;
};
case Jon:
{
std::cout << "Jon" << std::endl;
};
case Dany:
{
std::cout << "Dany" << std::endl;
};
}
}

You need to finish your switch cases with break statements, otherwise code continues to the next case label.
Counter-intuitive to some people, switch is not glorified multi-if statement, but rather a glorified goto statement. Every case label behaves like goto label, and absent of break, the code will simply continue executing.
This is often used in cases when two different case labels need to produce the same output - instead of duplicating the code, the labels are simply put one after another. For example:
switch (x) {
case 1: // fall through
case 2: work_one_or_two(); break;
...
}

You have to use break behind every case.
The switch/case rule is easy, after a mached case, all following cases will be executed until a break; or end of switch.

Related

Simple C++ error, "else without previous if" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm just getting started with C++ and I've run into an error. It tells me that I have an "else" without a previous "If", but I do. I checked the case of the code and it looks basically just like the example from the website I'm learning from, it just has different sentences after all the couts, so I don't know what's wrong. Any help will be much appreciated.
int main()
{
int iOud;
cout<<"Type in your age: ";
cin >> iOud; //"a variable for the person's age
cin.ignore();
if (iOud < 20 );{
cout<< "A message\n";
}
else if (iOud > 40 ) {
cout << "A message\n";
}
else {
cout << "A message\n";
}
cin.get();
}
Drop the ; from if (iOud < 20 );{
if (iOud < 20 ); is a valid statement, so the compiler does not emit an error until it finds the invalid } else if. That's why the compiler error appears odd on first inspection.
The ; after if (iOud < 20) terminates the if statement.
Drop it, and you'd be fine
You ended the if(...) sentence with ; so it doesn't recognize it at all it, just sees the else if and drops the error. Drop the ; at if (iOud < 20 ); {.
And may I recommend using Switch/Case, if you are using multiple if sentences, but as Sean mentioned in the comment, this wouldn't apply for your example of comparing range of values.

Acceptable use of a label and 'goto'? [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 7 years ago.
Improve this question
I am writing a tokenizer for a compiler. I have a while loop that loops over characters and then a switch that checks for certain conditions. I then need to exit both blocks to write the token:
Token token;
while (peekChar() != '\0')
{
switch (c = nextChar())
{
case '(':
token = Token(TOKEN_LEFT_PAREN, currentLine);
goto MakeToken;
// ... every other character, some with lots of logic
}
}
MakeToken:
// write the token
Is this an acceptable use of labels, or is there a better way? I have learnt to think of labels as just terrible practice, but surely there must be uses for them (or they wouldn't be implemented in the standard?). Thanks.
Generally, when we want to break several scopes at once, it means that we can make sub-functions; Something like:
bool HandleChar(char c)
{
switch (c)
{
case '(': {
Token token = Token(TOKEN_LEFT_PAREN, currentLine);
return true;
}
// ... every other character, some with lots of logic
}
}
And then:
while (peekChar() != '\0')
{
if (HandleChar(nextChar())) {
break;
}
}
// ...
You could implement the very same with break here, without needing to use goto.
The only time I found a only-slightly-revolting case of goto in C++ was in a complex state machine where developers took arduous care not to mess up local state.
Generally, a parser (or more specifically, a tokenizer) is the last place where I'd go for spaghetti coding -- if anything, this calls for using C++ in a more functional way.
I believe this is one of very few examples when goto is accepted however you could use a flag:
Token token;
bool flag = true;
while ((peekChar() != '\0') && flag)
{
switch (c = nextChar())
{
case '(':
token = Token(TOKEN_LEFT_PAREN, currentLine);
flag = false;
// ... every other character, some with lots of logic
}
}

Understanding this Switch statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So I tried running this piece of code and could not understand why it is giving me the output is giving me. If I input 4, why is the result 17?? I really don't get it. Can someone please explain?
#include<iostream>
using namespace std;
int main() {
int num;
int alpha = 10;
cout << "Enter a number :" << endl;
cin >> num;
switch(num) {
case 3:
alpha++;
break;
case 4:
case 6:
alpha = alpha + 3;
case 8:
alpha = alpha + 4;
break;
default:
alpha = alpha + 5;
}
cout << alpha << endl;
return 0;
}
If you don't have any break;in the body of acase(or something else that would exit the case, like agoto) execution will continue with the next case statement (it will fall through as it's usually known).
In your case entering 4 will do first the case 4:, then fall through tocase 6:and then tocase 8:and the end result will be alpha (10) + 3 + 4 = 17. since the case 8:has abreak;the switch statement will exit here.
On a side note, there's something called compound assignment +=that you can use to save some space, so instead of
alpha = alpha + 3;
you can do this:
alpha += 3;
A case statement works in the following way: The execution jumps to the matching case statement and continues until a break or the end of the switch block. Therefore, the statement after the case 8 is executed, too. So, 10+3+4=17.
Not writing a break at the end of a case block is considered as an error in most cases. In some cases it might be useful to continue with the execution, but this has to be commented very clearly to prevent confusions.

I want to blink the LED's in reverse order [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to reverse the code as it complete first time. For example pin 1-pin 2-pin 3-pin 4 (it's complete) now it should run as pin 4-pin 3-pin 2-pin 1.
I wrote this code but it's not working in reverse order. Please guide me in this way.
#include<htc.h>
__CONFIG(1,OSCSDIS & HSPLL);
__CONFIG(2,BORDIS & PWRTDIS &WDTDIS);
__CONFIG(3,CCP2RC1);
__CONFIG(4,LVPDIS & STVREN);
__CONFIG(5,UNPROTECT);
__CONFIG(6,WRTEN);
__CONFIG(7,TRU);
define _XTAL_FREQ 40000000
void delay_sec(unsigned char seconds) // This function provides delay in terms of seconds
{
unsigned char i,j;
for(i=0;i<seconds;i++)
for(j=0;j<100;j++)
__delay_ms(10);
}
void led_display(char a)
{
switch(a)
{
case 0: PORTB=0x01;PORTD=0x08; break;
case 1: PORTB=0x02;PORTD=0x04; break;
case 2: PORTB=0x04;PORTD=0x02; break;
case 3: PORTB=0x08;PORTD=0x01; break;
}
}
void main()
{
TRISB=0x00; TRISD=0x00; char a,b;
while(1) {
led_display(a);
a++;
delay_sec(1);
if(a==4) {
a--;
}
}
}
For doing that, you have to remember in which order you are running (reverse or not). So you will have a variable indicating if the order is reverse or not, and change it when you reach the extremities of your counter (0 and 3)
And you can optimize the code with using 1 and -1 for the variable which remembers order and adding it to a.
Your code will seem like this in your main :
int reverse = 1,
char a = 0;
while(1)
{
led_display(a);
delay_sec(1);
if(a==3)
{
reverse=-1;
}
if(a==0)
{
reverse=1;
}
a+=reverse;
}
Regards.

How to keep track of order in which switch case values are executed? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How can I keep track of the order in which switch case statements are executed?
For example:
while (some_boundary) {
switch (value) {
case a:
do something;
move to next value;
break;
case b:
do something;
move to next value;
break;
case c:
do something;
move to next value;
break;
}
}
I want to know if the switch was executed abc or bac or cab, etc.
Any idea ? Or will implementing via if/else make more sense ?
You can save a vector at every iteration with the value of the corresponding iteration:
std::vector<int> sequence;
while (some_boundary) {
int temp = computeValue(); // Or however you get your value.
sequence.push_back(temp);
switch (temp) {
case a:
//do something;
break;
case b:
//do something;
break;
case c:
//do something;
break;
}
}
Edit: This is assuming that value is set somewhere between the while and the switch, so you can save it in advance. Other option is to include the push_back instruction in every case, but is more "dirty". Preallocating the vector could save some computation time as well.
Edit2: code modified according the suggestions so that it is ensured that a new value will be computed.
If you just want to know (and not save the results) you could just output the value at each iteration. Try
cout << value << endl;
as the first line within the while loop.