Introduction
When attempting to compile code employing a switch statement with case ranges, you may encounter errors if the compiler does not support case ranges as an extension of the C standard. This article provides a solution to this issue.
Problem Encountered
The given code snippet:
#include <iostream> using namespace std; int main(){ int score; //Vraag de score cout << "Score:"; cin >> score; //Switch switch(score){ case >= 100: cout << "a"; break; // ... (other cases omitted) } return 0; }
generates compilation errors due to the use of case ranges (e.g., case >= 100).
Solution: Case Range Support
Some compilers support case ranges as an extension to C . To resolve the compilation issue, use the following syntax for case ranges:
case a ... b:
where a and b are the lower and upper bounds of the range.
Updated Code:
The updated code snippet would look like:
#include <iostream> using namespace std; int main(){ int score; //Vraag de score cout << "Score:"; cin >> score; //Switch switch(score){ case 0: cout << "a"; break; case 1 ... 9: cout << "b"; break; // ... (other cases omitted) } return 0; }
Note that the lower bound of the first case range (0) is inclusive, while the upper bound of all subsequent case ranges is exclusive.
The above is the detailed content of How to Resolve Compilation Errors When Using Case Ranges in Switch Statements?. For more information, please follow other related articles on the PHP Chinese website!