The following code uses a switch with enum. The main program passes the argument correctly to the function, but the correct switch line is not executed. Can you advise why it is not entering the switch conditions?
enum MyEnum {
Enum1 = 1,
Enum2 = 0x0D
};
bool compute(MyEnum code) {
switch(code) {
Enum1: return true;
Enum2: return false;
};
cout << "why here??" << endl; // this line is getting printed for both inputs
return false;
}
int main() {
cout << "compack=" << compute((MyEnum)1) << endl; // printed "0"
cout << "compack=" << compute((MyEnum)13) << endl; // printed "0"
}
I checked the other questions related to switch and enum (eg 3019153), but cant figure out the bug.
You are missing the case keyword:
switch(code) {
case Enum1: return true;
case Enum2: return false;
};
switch(code)
{
case Enum1: return true;
case Enum2: return false;
};
You forgot to write case
switch(code)
{
case Enum1: return true;
case Enum2: return false;
};
A generic switch is like:
switch(var)
{
case val1:
foo();
break;
case val2:
bar();
break;
default:
error();
};
You forgot case there..
switch(code)
{
case Enum1:
//do something
break;
case Enum2:
//do something
break;
};
Okay, so others have answered that you are missing the case keyword. What hasn't been explained, though, is why the original code compiled. That's because without the case keyword, it was treated as a goto label. In fact, this compiles:
switch (i) {
if (j == 3) {
case 1:;
L1:;
} else {
goto L1;
case 2:;
}
}
Note that the j==3 is actually dead code. It can never be executed. For an actual useful application of this, see Duff's device. By the way, compiling with full warnings enabled would have warned you about an unused goto label, at least with g++ and clang++ (-Wall -Wextra -pedantic).
Related
playpen pp;
bool more(true);
do{
display_content();
int const choice(get_choice));
more = do_choice(pp, choice);
} while (more)
function code >>
bool do_choice(int choice){
bool more(true);
switch(choice){
case 0:
clear_playpen(???);
break;
case 1:
more = false;
break;
case 2:
change_plotmode(???);
break;
case 3:
plot_pixel(???);
break;
case 4:
change_scale(???);
break;
default:
throw problem("Not a valid option");
}
return more;
}
the do_choice function has a declaration bool do_choice(int choice);
with the last line in definition as return true to the bool type. Why will the author again in the cpp script above say more = do_choice(...) which I am understanding to mean true = true // what use is that? Sounds gibberish to me
You're confusing the assignment operator (=) with the comparison operator (==).
The call to do_choice updates more so the loop will stop eventually.
This yields warning C4715: not all control paths return a value.
int f_no_default(bool true_or_false)
{
switch (true_or_false)
{
case (true) :
return 1;
case (false) :
return 0;
}
}
But this yields warning C4809: switch statement has redundant 'default' label; all possible 'case' labels are given.
int f_with_default(bool true_or_false)
{
switch (true_or_false)
{
case (true) :
return 1;
case (false) :
return 0;
default:
return 0;
}
}
What can I do? (other than turn off treat warnings as errors)
Visual Studio 2013 V12.0
What can I do? (other than turn off treat warnings as errors)
The following code might probably fix it:
int f_no_default(bool true_or_false)
{
switch (true_or_false)
{
case (true) :
return 1;
case (false) :
return 0;
}
return 0; // <<<<<<<<<<<<<<<<<
}
That's a silly warning for the case, but the static analysis capabilities depend on the actual compiler implementation, so do the usefulness of warning messages.
Another option (more compliant with your function name) would be to throw an exception:
int f_no_default(bool true_or_false)
{
switch (true_or_false)
{
case (true) :
return 1;
case (false) :
return 0;
}
throw std::runtime_error("Unecpected value for 'true_or_false'");
}
I am in a beginning C++ programming class and I need help with nesting switch statements and using multiple conditions, because I have to translate a program I already wrote from if/else statements to switch statements, because I didn't know I was supposed to use the switch statement.
For example, how do I change something like:
if (temperature >= -459 && temperature <= -327)
{
cout << "Ethyl Alcohol will freeze.\n";
}
else if (temperature >= -326 && temperature <= -30)
{
cout << "Water will freeze.\n";
}
else if ...
{
}
else
{
}
Into a switch/case statement? I can get the first level, but how do I nest and have multiple conditions like the temperature statements above?
Switch statements work like this:
int variable = 123; // or any other value
switch (variable)
{
case 1:
{
// some code for the value 1
break;
}
case 12:
{
// some code for the value 12
break;
}
case 123:
{
// some code for the value 123
break;
}
case 1234:
{
// some code for the value 1234
break;
}
case 12345:
{
// some code for the value 12345
break;
}
default:
{
// if needed, some code for any other value
break;
}
}
First of all, this question is in C and not in C++. C++ inherited most of the C language, including the switch-case.
You can't do this with a switch, unless you start enumerating all the values one by one, like this:
switch (temperature) {
case -459:
case -458:
....
case -327: <do something>; break;
case -326:
.....
}
This is because in C, switch-case is simply translated to a series of if-goto statements, with the cases just being the labels.
In your case, your stuck with an if-else-if ladder.
You could use a lookup table that has temperatures and the text to print:
struct Temperature_Entry
{
int min_temp;
int max_temp;
const char * text_for_output;
};
static const Temperature_Entry temp_table[] =
{
{-459, -327, "Ethyl Alcohol will freeze.\n"},
{-326, -30, "Water will freeze.\n"},
};
static const unsigned int entry_count =
sizeof(temp_table) / sizeof(temp_table[0]);
//...
int temperature;
for (unsigned int i = 0; i < entry_count; ++i)
{
if ( (temperature >= temp_table[i].min_temp)
&& (temperature < temp_table[i].max_temp))
{
std::cout << temp-table[i].text_for_output;
}
}
As many have pointed out, you cannot use switch case for ranges and dynamic formulas. So if you want to use them anyway, you will have to write a function which takes a temperature and returns a temperature range out of a pre-known set of temperature ranges. Then, finally, you can use a switch/case for the temperature ranges.
enum TemperatureRange { FrigginCold, UtterlyCold, ChillinglyCold, Frosty, ... };
TemperatureRange GetRange( int temperature );
// ...
switch( GetRange( temperature ) )
{
case FrigginCold: cout << "The eskimos vodka freezes."; break;
case UtterlyCold: cout << "The eskimo starts to dress."; break;
// ...
}
I have a piece of code pretty similar to this:
class someclass
{
public:
enum Section{START,MID,END};
vector<Section> Full;
void ex(){
for(int i=0;i<Full.size();i++)
{
switch (Full[i])
{
case START :
cout<<"S";
break;
case MID :
cout<<"M";
break;
case END:
cout<<"E";
break;
}
}
}
};
Now imagine I have much more enum types and their names are longer....
well what i get is not a very good looking code and i was wondering if it possible to bind a specific char to an enum type and maybe do something like this:
for(int i=0;i<Full.size();i++)
{
cout<(Full[i]).MyChar();
}
Or any other method that could make this code "prettier".
Is this possible?
Unfortunately there is not much you can do to clean this up. If you have access to the C++11 strongly typed enumerator feature, then you could do something like the following:
enum class Section : char {
START = 'S',
MID = 'M',
END = 'E',
};
And then you could do something like:
std::cout << static_cast<char>(Full[i]) << std::endl;
However, if you do not have access to this feature then there's not much you can do, my advice would be to have either a global map std::map<Section, char>, which relates each enum section to a character, or a helper function with the prototype:
inline char SectionToChar( Section section );
Which just implements the switch() statement in a more accessible way, e.g:
inline char SectionToChar( Section section ) {
switch( section )
{
default:
{
throw std::invalid_argument( "Invalid Section value" );
break;
}
case START:
{
return 'S';
break;
}
case MID:
{
return 'M';
break;
}
case END:
{
return 'E';
break;
}
}
}
In a situation like this you could be tricky and cast your chars.
enum Section{
START = (int)'S',
MID = (int)'M',
END = (int)'E'
};
...
inline char getChar(Section section)
{
return (char)section;
}
I think the best solution in this case would be to use a map:
#include <iostream>
#include <map>
class someclass
{
public:
enum Section{START = 0,MID,END};
map<Section,string> Full;
// set using Full[START] = "S", etc
void ex(){
for(int i=0;i<Full.size();i++)
{
cout << Full[i];
}
}
};
This question already has answers here:
Case expression not constant
(5 answers)
Closed 5 years ago.
Here is my code:
bool Character::keyPress(char c)
{
switch(c)
{
case up_key:
move(0, -1);
break;
case down_key:
move(0, 1);
break;
case left_key:
move(-1, 0);
break;
case right_key:
move(1,0);
break;
default:
return false;
}
return true;
}
And the compiler complains:
error C2051: case expression not constant
error C2051: case expression not constant
error C2051: case expression not constant
error C2051: case expression not constant
In my header file I have:
protected:
char up_key;
char down_key;
char right_key;
char left_key;
I am using Visual C++ 2008.
As the error message states, the case expressions must be constant. The compiler builds this as a very fast look-up table at compile time and it can't do that if there is a possibility that the values could change as the program runs.
If you do need them to be variable, not constant, your best bet is to use if/else statements instead.
Replace this long clumsy code,
switch(c)
{
case up_key:
move(0, -1);
break;
case down_key:
move(0, 1);
break;
case left_key:
move(-1, 0);
break;
case right_key:
move(1,0);
break;
default:
return false;
}
with something like this:
move( (c==right_key) - (c==left_key) , (c==down_key) - (c==up_key) );
You can litterly replace that 17 lines long of code with that much more neat single line of code.
You can't because the language doesn't work that way. For example, what would happen if up_key, down_key, right_key, and left_key were all equal?
Because the switch statement can take only constants, you know when reading the code that the things you're comparing against are all constants. On the other hand, you would use if statements (or some other structure) to compare against variables:
if (c == up_key) {
move(0, -1);
} else if (c == down_key) {
move(0, 1);
} else ...
This provides a distinct difference in structure which can greatly aid those who come after you in reading your code. Imagine if you had to look up every case label to see whether it was a variable or not?
I believe it's because the compiler generates a jump table, with the values hardcoded in, although I may be wrong. The way the tables are generated just doesn't allow for it.
Since other answers have covered why you are getting an error, here is a way to move in one of the four directions in response to a key press: use lookup tables instead of the conditionals/switches.
Setup portion:
std::map<char,pair<int,int> > moves;
moves[up_key] = make_pair(0, -1);
moves[down_key] = make_pair(0, 1);
moves[left_key] = make_pair(-1, 0);
moves[right_key] = make_pair(1, 0);
The function:
bool Character::keyPress(char c) {
if (moves.count(c)) {
pair<int,int> dir = moves[c];
move(dir.first, dir.second);
return true;
} else {
return false;
}
}
//here is the full functional code snippet which can be compiled and run with most of C++
//compiler/link ...console app was demoed but you can apply the code/logic to win32 app...
//if you have any problem, send me email to Samuel_Ni#yahoo.com
#include <iostream.h>
#include <map>
#include <conio.h>
class CkbdHanler{
private:
map<char,pair<int,int> > moves;
protected:
char up_key;
char down_key;
char right_key;
char left_key;
public:
CkbdHanler(char a,char b,char c,char d):up_key(a),
down_key(b),
right_key(c),
left_key(d)
{
moves[up_key] = make_pair(0, -1);
moves[down_key] = make_pair(0, 1);
moves[left_key] = make_pair(-1, 0);
moves[right_key] = make_pair(1, 0);
}
bool keyPress(char c){
if (moves.count(c)) {
pair<int,int> dir = moves[c];
move(dir.first, dir.second);
return true;
} else return false;
}
void move(int i,int j){
cout<<"(i,j)=("<<i<<","<<j<<")"<<endl;
}
};
int main(int argc, char* argv[])
{
CkbdHanler CmyKbdH('u','d','l','r');
cout << "Hello C++... here is a demo of Map to replace switch-case" << endl;
CmyKbdH.keyPress('d');
cout << endl << "Press any key to continue...";
getch();
return 0;
}