Selecting a Range of Values in a Switch Statement
In the example provided, the compiler encounters errors due to an invalid syntax in the switch statement. The code attempts to specify ranges of values using the syntax "case >= value" and "case == value," which is not standard in C .
To resolve the issue, it's important to note that some compilers support case ranges as an extension to the C language. The syntax for specifying a range of values is "case value ... value."
Revised Code with Case Ranges:
#include <iostream> using namespace std; int main() { int score; // Get score from user cout << "Score: "; cin >> score; // Switch statement with case ranges switch (score) { case 0: cout << "a"; break; case 0 ... 9: cout << "b"; break; case 11 ... 24: cout << "c"; break; case 25 ... 49: cout << "d"; break; case 50 ... 100: cout << "e"; break; default: cout << "BAD VALUE"; break; } cout << endl; return 0; }
Compiler Support for Case Ranges:
Case ranges are not supported in all compilers. Here are some known compilers that support this feature:
If your compiler does not support case ranges, you will need to use a different approach for selecting a range of values in a switch statement. One option is to use a series of nested if-else statements as follows:
if (score >= 100) { cout << "a"; } else if (score >= 50) { cout << "b"; } else if (score >= 25) { cout << "c"; } else if (score >= 10) { cout << "d"; } else if (score > 0) { cout << "e"; } else if (score == 0) { cout << "f"; } else { cout << "BAD VALUE"; }
The above is the detailed content of How to Implement Range-Based Cases in a C Switch Statement?. For more information, please follow other related articles on the PHP Chinese website!