Any situation where you can't use a Switch statement in C++
Hey everyone, I'm in programming languages class and the instructor just asked if there is any situation where you can't use a switch statement and can only use if statements. So far I've been able to write everything from any kind of if statement example into code in a switch statement. Anyone have any ideas of a situation that you HAVE to use an if and it is impossible to use a switch?? I don't think there is...
i think yes:
how would you write;
if( i < 50000 )
doSomething();
i is a float?
you will have to gave many many case's ;)
how would you write;
if( i < 50000 )
doSomething();
i is a float?
you will have to gave many many case's ;)
The expression in the switch statement must be an integral type - char, short, int, long, enumeration, etc.
It can't be used with floats, strings, etc.
It can't be used with floats, strings, etc.
You can only use switch for integer types ( int, short, long, char ) and enum's ( which are considered integers ). So floating point types ( float, double ) and strings ( both char* and std::string ) won't work.
Edit: Too slow :(
Edit: Too slow :(
//Well, how I did them was I changed
If(stringA == stringB)
cout<<"They are the same";
//to this switch
bool temp;
temp = (stringA == stringB);
switch(temp){
case 1:
cout<<"They are the same"
}
//Basically that's how I did it, was create a temporary boolean value and did the compare statement which would put either true of false (1 or 0) into the temp variable and did the switch on that...is that valid?
If(stringA == stringB)
cout<<"They are the same";
//to this switch
bool temp;
temp = (stringA == stringB);
switch(temp){
case 1:
cout<<"They are the same"
}
//Basically that's how I did it, was create a temporary boolean value and did the compare statement which would put either true of false (1 or 0) into the temp variable and did the switch on that...is that valid?
It's valid, but it's very stupid. Is there a reason you wish to avoid using if? A switch (with enough case labels) gets compiled into a jump table, and an if gets compiled into a jump. You don't gain or lose anything for a single test (actually, you lose because of your temporary).
switch(stringA == stringB){case 1:cout<<"They are the same"}
In case you really want to use switch without a temporary variable, but that switch doesn't make sense anyway.
No, it doesn't make sense, haha. But I'm not trying to make the switch make sense, I'm just trying to make sure ANYTHING you can do in an if statement, you can do in a switch. For example, lets say they come out with a C++++ language or something that is C++, word for word, except there are no if statements at all in this new language. Could you do everything with this new language that you could with c++ by using switch statements for the logic instead of the ifs which no longer exist? That's all I'm trying to ask.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement