Reputation: 85
i am new to C++ and currently learning switch statements, but i don't know why does my compiler throws an error or warning (in case of booleans) when i use boolean, float, & string ?
How can i solve the problem ? or why does it occur
Upvotes: 0
Views: 629
Reputation: 11311
First, you can use boolean in a switch statement:
int main(int argc, char** argv) {
bool b = argc > 1;
switch (b) {
case true:
break;
case false:
break;
}
}
As commented above, the float
's are not suitable for equality test.
And since you asked "How can i solve the problem ?", for the string I would suggest an unordered map:
std::unordered_map<std::string, int> m = { {"abc", 1}, {"qwe", 2} };
switch(m["foo"]) {
case m["abc"]:
...
}
Upvotes: 0
Reputation: 57678
In days of old and sometimes today, switch
statements were translated into arrays of branch or jump statements, preferably contiguous.
As with arrays, indices of 8.9, "frog", and "false" don't make sense.
The C and C++ languages are designed for efficiency when compiled. An array of jump instructions is much more efficient than having to do an "if-else-if" ladder, which is required for other index types (such as floating point and text or string).
For those pedantic readers:
Using integers as case values allows for better optimization (implementation) of the decision structure. Contiguous (consecutive) case values allow for better optimization or implementation. An optimal decision structure is an array of jump, branch instructions or pointers to functions.
For example, an optimum implementation would be:
destination_address = switch_table[case_value];
Many processors can implement this with a single instruction.
Other languages may implement a table of <case_value, destination_address>. One issue with floating point case values is that comparing for equality with floating point is difficult because not all numbers can be represented exactly by floating point. For example if you have case 3.14:
and your index is 3.14159
, is the case activated?
For string or text case-values, enough characters must be compared to determine equality. For example, "hyperbolic" and "hyperthreading" need to go through 5 iterations to determine equality. Hashing could be used, but there may be more execution with the hashing function than there are letters to compare.
So, to allow compact and efficient implementations of switch
statements, the authors of the C and C++ language decided to restrict the case
values to integers. Other forms, like strings, will require an if-else-if
ladder, table search or dictionary (map).
Upvotes: 2