Home > Backend Development > C++ > How to Implement Range-Based Cases in a C Switch Statement?

How to Implement Range-Based Cases in a C Switch Statement?

Linda Hamilton
Release: 2024-11-13 10:34:02
Original
1077 people have browsed it

How to Implement Range-Based Cases in a C   Switch Statement?

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;
}
Copy after login

Compiler Support for Case Ranges:

Case ranges are not supported in all compilers. Here are some known compilers that support this feature:

  • GCC 4.9 and later
  • Clang 3.5.1 and later
  • Intel C/C Compiler 13.0.1

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";
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template