The usage of switch in C language is: 1. The [expression] in brackets after switch, the ANSI standard allows it to be of any type; 2. When the value of the expression matches the constant expression after a case When the values are equal, the statement following this case is executed; otherwise, the statement following default is executed.

The usage of switch in C language is:
Function: The switch statement is a multi-branch selection statement. Used Implement a multi-branch selection structure. The if statement has only two branches to choose from, but multi-branch selection is often used in practical problems. For example, student performance classification (90 is "A", etc., 80-89 is divided into 'B' etc., 70-90 is divided into 'C', etc...). Of course, these can be handled with nested if statements, but if there are many branches, there will be many layers of nested if statements, and the program The redundancy is long and the readability is reduced. The C language provides the switch statement to directly handle multi-branch selections, which is equivalent to the CASE statement in the PASCAL language.
Form: switch (expression)
{
case 常量表达式 1:语句 1
case 常量表达式 2:语句 2
.
.
.
case 常量表达式 n:语句 n
default:语句 n+1
}For example, if you want to print out the hundred-point score segment according to the test score level, you can use the switch statement:
switch(grade)
{
case 'A':printf("85-100\n");
case 'B':printf("70-84\n");
case 'C':printf("60-69\n");
case 'D':printf("<60\n");
default:printf("error\n");
}Description:
(1) The "expression" in the brackets after the switch, ANSI The standard allows it to be of any type.
(2) When the value of the expression is equal to the value of the constant expression following a case, the statement following the case will be executed. If the constants in all cases If the value of the expression does not match the expression, the statement after default will be executed.
(3) The value of the constant expression in each case must be different from each other, otherwise there will be conflicts. Phenomenon (there are two or more execution plans for the same value of an expression).
(4) The order in which defaults appear in each case does not affect the execution results. For example, "default: ..." can appear first, then "case 'D': ...", and then "case 'A': ...".
(5) After execution After the statement following a case, the flow control is transferred to the next case to continue execution. The "case constant expression" only serves as a statement label, and does not perform conditional judgment there. When executing the switch statement, according to the expression following the switch If the matching entry label is found, the execution will start from this label without further judgment. For example, in the above example, if the value of grade is equal to 'A', it will be continuously output:
85-100 70-84 60-69 <60 error
Therefore, it should After executing a case branch, make the process jump out of the switch structure, that is, terminate the execution of the switch statement.
You can use a break statement to achieve this purpose. Rewrite the above switch structure as follows:
switch(grade)
{
case 'A':printf("85-100\n"); break;
case 'B':printf("70-84\n"); break;
case 'C':printf("60-69\n"); break;
case 'D':printf("<60\n"); break;
default:printf("error\n");
}The last branch (default) does not need to add a break statement. If the value of grade is 'B', only "70-84" will be output.
Although there is more than one execution statement behind the case, it can There is no need to enclose it in curly brackets, all execution statements following this case will be automatically executed sequentially. Of course, curly brackets can also be added.
(6) Multiple cases can share a set of execution statements, for example:
case 'A':
case 'B':
case 'C': printf(">60\n");break;
.
.The same set of statements is executed when the value of grade is 'A', 'B' or 'C'.
Related learning recommendations: C video tutorial
The above is the detailed content of What is the usage of switch in C language?. For more information, please follow other related articles on the PHP Chinese website!
C# var keyword best practicesJul 21, 2025 am 03:02 AMWhen using var, it should be determined based on whether the type is clear and whether the readability is affected. 1. When the type is clear on the right side of the assignment, such as varlist=newList(); can improve the code simplicity; 2. When the type is fuzzy or returns to object or interface type, var should be avoided, such as IEnumerableresult=SomeMethod(); to improve readability; 3. Use var reasonably in anonymous types and LINQ queries, such as receiving anonymous objects, but subsequent processing is recommended to encapsulate it as a specific type; 4. In team projects, coding style should be unified, and var should be used reasonably through .editorconfig or code review to avoid abuse and affect maintenance.
How to compare two strings in C#?Jul 21, 2025 am 02:49 AMComparing strings in C# should be based on the scene selection method. The == operator is case-sensitive by default and compared based on the current culture, but is not suitable for complex scenarios. 1. Using the == operator is suitable for quick comparison, but may not meet the expected results due to culture or case; 2. Using String.Equals() and passing in StringComparison enumeration can achieve more precise control, such as Ordinal, OrdinalIgnoreCase, InvariantCulture, etc.; 3. Pay attention to handling null or empty strings when comparing. It is recommended to use the string.Equals() static method or use string.IsNullOrEmpt first.
How to format a DateTime to a custom string in C#?Jul 21, 2025 am 02:46 AMThe most common method of formatting DateTime objects into custom strings in C# is to use the ToString() method and pass in the format string, which includes: 1. Use standard format strings such as "d", "D", "t", and "T" to quickly implement common date and time formats; 2. Accurately control the output format through custom format strings such as "yyyy-MM-dd", "dd/MM/yyyyHH:mm"; 3. Use CultureInfo to handle format differences in different cultural environments to adapt to multilingual users.
C# LINQ query syntax vs method syntaxJul 21, 2025 am 02:38 AMThe query syntax or method syntax of LINQ should be selected according to the scene. ① Query syntax is suitable for SQL-like expressions, such as multi-step filtering, projection, sorting, multi-table joining, grouping statistics, etc., with clear and intuitive structure; ② The method syntax is more flexible, supports chain calls and dynamic query conditions construction, and is suitable for aggregation functions, asynchronous operations and scenarios where splicing logic is required; ③ Some operations such as Take, Skip, Any, etc. can only use method syntax. The two functions are the same, and the choice mainly depends on personal habits and specific needs. Reasonable mixing of the two can improve the readability and maintenance of the code.
How to create a custom exception in C#?Jul 20, 2025 am 01:43 AMThe core of creating custom exceptions in C# is to inherit the Exception class or its subclasses to improve the accuracy of error messages and code maintainability. 1. Custom exceptions can more specifically express error scenarios in business logic, such as InvalidLoginException clearly indicates login problems; 2. Its benefits include improving code readability, better distinguishing error types, and conveniently handling specific exceptions in a unified manner; 3. When creating, you need to inherit the Exception class and implement at least three constructors without parameters, with message parameters, with message and internal exceptions; 4. If serialization support is required, you can implement the ISerializable interface; 5. Throw it when a specific error condition is detected, such as using thrown when verification fails.
What are lambda expressions in C#?Jul 20, 2025 am 01:20 AMLambda expressions are used in C# to write inline, anonymous functions that can be used anywhere you need to delegate. They are simple and flexible, especially suitable for LINQ or asynchronous code. Lambda expressions use the => operator, on the left are input parameters, on the right are expressions or statement blocks; for example, x=>xx represents a lambda that accepts x and returns its squared. If there are multiple parameters, it needs to be wrapped in brackets, such as (intx,inty)=>x y, the type can be omitted and inferred by the compiler. Common uses include LINQ query, event processing, asynchronous programming, etc., such as numbers.Where(n=>n%2==0) filtering even numbers. Unlike the conventional method, lambda
C# thread vs task: which is better?Jul 20, 2025 am 01:10 AMIn C#, Thread is suitable for underlying scenarios that require fine control of threads, such as long-running services or exclusive resource tasks; Task is recommended for modern application development because it is based on thread pools, supports asynchronous waiting, has advanced functions and is more efficient. 1.Thread directly operates operating system threads, suitable for background services and tasks that clearly require exclusive threads, but create and destroy costs, consume high resources, and lack a built-in asynchronous mechanism. 2.Task automatically utilizes thread pools to save resources, supports cancellation, exception handling, await and other features, and is commonly found in UI optimization, parallel computing, I/O operation and other scenarios. 3. The key difference between the two is: Thread is an underlying implementation, with high resource consumption and fine control granularity, while Task abstraction
How to parse a string to an enum in C#?Jul 20, 2025 am 12:59 AMWhen parsing a string into an enum type in C#, you should preferentially use the Enum.TryParse method to avoid exceptions, and combine Enum.IsDefined to ensure the value is legal. 1. Use Enum.TryParse to safely parse strings, return a Boolean value to indicate success or not, and support ignoring case; 2. Can handle entire numeric strings such as "1", and still ensure that the value actually exists in the enum definition; 3. Enum.IsDefined must explicitly verify whether the parsing result is a valid member of the enum to prevent illegal values from being mistakenly considered valid. Mastering these key points ensures the robustness of the string-to-enum conversion.


Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use







