learn_C_deep_7 (Basic understanding of switch statement, role of case, role of break switch, case recommendation rules)

Table of contents

Basic understanding of switch statement

In-depth understanding of case statements

The role of case

case statement requirements

The role of break

switch case recommended rules

Rule one:

Rule two:

summary:


Basic understanding of switch statement

        switch is a control statement used to control the direction of program flow. In a switch statement, a specific block of code can be executed based on the value of an expression. A switch statement consists of an expression and multiple case blocks. The value of the expression is first evaluated, and then the corresponding value is matched in the case block. If the match is successful, execute the code in the case block, and then jump out of the switch statement. If none of the case blocks match successfully, the default code block is executed.

switch ( integer variable/constant/integer expression ) { case var1:     break; case var2:     break; case var3:     break; default:     break; }








Next let's look at a piece of code

//#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#pragma warning(disable:4996)
int main()
{
	int day = 0;
	scanf("%d", &day);
	//if语句具备两个功能
	//1.判断
	//2.分支
	//switch-case-break也具备这个功能
	//但是switc不具备判断和分支的能力,它仅仅做的是拿day的值去进行匹配
	switch (day)
	{
	case 1://1.判断
		printf("星期一!\n");
		break;//2.分支
	case 2:
		printf("星期二!\n");
		break;
	case 3:
		printf("星期三!\n");
		break;
	case 4:
		printf("星期四!\n");
		break;
	case 5:
		printf("星期五!\n");
		break;
	case 6:
		printf("星期六!\n");
		break;
	case 7:
		printf("星期天!\n");
		break;
	}
	return 0;
}

        This is a program written in C language. First, the program uses the ` #define` preprocessing directive to define a macro `_CRT_SECURE_NO_WARNINGS` to eliminate security warnings (scanf) . The `#include` directive includes the `stdio.h` header file, which provides declarations of standard input/output functions. Next, the program uses the `#pragma` directive to disable specific warnings. The ` #pragma warning(disable:4996) ` directive here does not perform compiler inspection and compile output on specific warning output in Visual Studio.

        In the `main` function, the program defines an integer variable `day`, and calls the `scanf` function to read an integer and save it in ` day` . The program then uses the `switch` statement to output the corresponding information based on the value of `day`. If the value of `day` matches any `case`, output a specific string, and then use the `break` statement to jump out of the execution of the `switch` statement. If none of the `day` values ​​match any of the `case`s, nothing will be output. Finally, the `main` function returns 0 to indicate normal program termination.

        Overall , this program demonstrates the ability to use `switch` statements to implement multiple branch selections, optimizing code readability and maintainability when using multiple `if...else` statements.

In-depth understanding of case statements

The role of case

        In C language, `case` is a keyword used in `switch` statement. The `switch` statement can choose which statement block in the `case` branch to execute according to the value of the expression.

The essence of the case is to perform the judgment function.

case statement requirements

switch(m) && case n
//What type of variable or expression must m and n be?

//The value after the case statement is required to be a constant expression or an enumeration type or a macro definition

                        , that is, an expression whose result can be evaluated at compile time .
//Can the case statement be followed by a const-modified read-only variable? No
#include <stdio.h>
#include <windows.h>
int main()
{     const int a = 10;     switch (a) {// Yes - a is a constant     case a: // No - error C2051: case expression The formula is not a constant         printf("hello\n");         break;     default:         break;     }     system("pause");     return 0; }










Is there any error in the following code?

case 1:
        int a = 1;
        print("%d\n",a);
        break;

       

        In C language, no new variable can be defined in the case statement. This is because in the C language, the syntax of the switch-case statement stipulates that the case branch can only contain statements, not declaration statements.

If we need to use a variable in the case branch, we can define the variable before the switch statement, or add {} when adding the definition, or encapsulate it into a function

1.

int a = 1;
    switch (day)
    {
    case 1:
        printf("%d\n", a);
        break;

2.

case 1:
	{
		int a = 1;
		printf("%d\n", a);
	}
		break;

3.

void test()
{
	int a = 1;
	printf("%d\n", a);
}
	

    case 1:
		test();
		break;

The role of break

        In the `switch` statement, `break` is used to end the current branch and jump out of the entire `switch` statement.

The essence of break is actually a branch function.

What if we don't have a break in the switch statement?

        This is a piece of C language code that uses a switch-case statement. Its function is to output the string of the corresponding day of the week according to the input number day (indicating the day of the week). First read the value of day through the scanf function, and then use the switch-case statement to judge. In the switch statement, for each possible day value, there is a corresponding case branch, and the corresponding strings are output respectively. It should be noted that no break statement is used in the case branch, which means that after a case branch is matched, the execution will continue until the next break or switch statement is encountered. Therefore, if the input day is 5, the output is not only "Friday!" but also "Saturday!" , "Sunday!" , and then the switch statement ends.

Summary : The last statement of each `case` branch must be a `break` statement, otherwise the program will continue to execute the code of the next branch until it encounters a `break` statement or the end of a `switch` statement.

switch case recommended rules

Rule one:

What if we want to print "working days" from Monday to Friday, and print "rest days" from Saturday to Sunday?

#include<stdio.h>
#pragma warning(disable:4996)
int main()
{
	int day = 0;
	scanf("%d", &day);

	switch (day)
	{
	case 1:
		printf("工作日!\n");
		break;
	case 2:
		printf("工作日!\n");
		break;
	case 3:
		printf("工作日!\n");
		break;
	case 4:
		printf("工作日!\n");
		break;
	case 5:
		printf("工作日!\n");
		break;
	case 6:
		printf("休息日!\n");
		break;
	case 7:
		printf("休息日!\n");
		break;
	}
	return 0;
}

Although the above writing method is feasible, but there are many repeated sentences, we can change the writing method at this time.

#include<stdio.h>
#pragma warning(disable:4996)
int main()
{
	int day = 0;
	scanf("%d", &day);

	switch (day)
	{
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		printf("工作日!\n");
		break;
	case 6:
	case 7:
		printf("休息日!\n");
		break;
	}
	return 0;
}

Summary: If multiple different cases match and want to execute the same statement, we can save the previous case statement and only keep the last case statement.

Rule two:

        In the above program, if we input any number other than 1-7, the program has no running results, so when the user uses the code, the code experience is very insufficient, because you input anything other than 1-7 Any number, the program does not report an error, and the user does not know what to input and what error is prompted. So we have to improve the code above.

#include<stdio.h>
#pragma warning(disable:4996)
int main()
{
	int day = 0;
	printf("Please enter your day:>");
	scanf("%d", &day);

	switch (day)
	{
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		printf("工作日!\n");
		break;
	case 6:
	case 7:
		printf("休息日!\n");
		break;
	default:
		printf("你输入的值有误!\n");
	}
	return 0;
}

 Summary: default is a keyword for the "default (default)" branch in the switch-case statement structure. The default branch represents the code to execute when none of the case branches match. It should be noted that the default branch can be placed anywhere in the switch statement. But usually, it is recommended to put the default branch at the end of the switch statement, so as to better understand the logic of the code.

summary:

1. In the switch statement, case completes the judgment function, break completes the branch function, and default completes the handling of abnormal situations.

2.case expression:

        sentence;

        2.1. If the relationship between the expression and the statement is one-to-many (the case has multiple statements), the variable cannot be defined in the case at this time. If necessary, use a function or {} or define the variable outside the switch.

        2.2. If the relationship between the expression and the statement is many-to-one, it is recommended to save the break statement after executing the case of the same statement, and only need to keep the last one.

3. default can appear anywhere in the switch, it is recommended to put it at the end.

4.case: The expression must be converted into a value at compile time, it can be a macro, but the variable modified by const cannot.

Guess you like

Origin blog.csdn.net/qq_64446981/article/details/130374564