Home >Backend Development >C++ >Can I Use Ranges in Case Statements in a C Switch Statement?
How do I Select a Range of Values in a Switch Statement in C ?
In C , a switch statement allows you to execute different code depending on the value of a variable. Typically, you use individual case statements for each value you want to check. However, in some programming languages, you can use a range of values in a case statement.
For example, consider the following code:
switch (score) { case >= 100: // ... break; case >= 50: // ... break; // ... }
This code is attempting to use a range of values in the case statements, but it will result in a compiler error because C does not support this syntax.
To fix this problem, you can use a series of individual case statements for each value in the range. For example:
switch (score) { case 100: case 101: case 102: // ... break; case 50: case 51: case 52: // ... break; // ... }
Alternatively, some compilers may support an extension to the C language that allows you to specify a range of values in a case statement using the following syntax:
switch (score) { case 0 ... 9: // ... break; case 10 ... 24: // ... break; // ... }
However, it is important to note that this extension is not supported by all compilers, so it is best to avoid using it if you need to support multiple compilers.
The above is the detailed content of Can I Use Ranges in Case Statements in a C Switch Statement?. For more information, please follow other related articles on the PHP Chinese website!