Branch statement (detailed)

Keywords: C

if statement

1. Grammatical Structure

1. Structure

//Single Branch
If (expression)
Statement;

//Bibranching
If (expression)
Statement 1;
else
Statement 2;

//Multi-Branch Structure
If (expression 1)
Statement 1;
Else if (expression 2)
Statement 2;
......
else
Statement n;

2. Examples

#include <stdio.h>
//Code 1
int main()
{
 int age = 0;
    scanf("%d", &age);
    if(age<18)
   {
        printf("Under age\n");
   }
  return 0;
}
//Code 2
#include <stdio.h>
int main()
{
 int age = 0;
    scanf("%d", &age);
    if(age<18)
   {
        printf("Under age\n");
   }
    else
   {
        printf("adult\n");
   }
  return 0;
}
//Code 3
#include <stdio.h>
int main()
{
 int age = 0;
    scanf("%d", &age);
    if(age<18)
   {
        printf("juvenile\n");
   }
    else if(age>=18 && age<30)
   {
        printf("Youth\n");
   }
    else if(age>=30 && age<50)
   {
        printf("middle age\n");
    }
    else
    {
         printf("old age\n");
    }
    return 0;
}
/*Explain: 
If the result of the expression is true, the statement executes.
How do you represent authenticity in C?
0 Represents false, non-zero represents true.*/

2. Points for Attention

1. A branch can only control one statement or block of code

If the if statement condition is true, if you want to execute multiple statements, you must enclose multiple statements with code blocks. A pair of {} is a code block.

//Code 1
if (a>5)
	printf("a Greater than 5");
	a++;
//Code 2
if (a>5)
{
	printf("a Greater than 5");
	a++;
}
//The meaning of the two pieces of code here is different. Code 1 executes printf("a is greater than 5") if the condition is true; the branch statement ends and a++ is executed afterwards;That is, code 1 always executes a++, regardless of the condition.Code 2, however, only executes a++; if the condition is true.

2. In multi-branch statements, if matches the closest and unmatched if to else

In a multi-branch statement, if an if cannot be matched with an else, the first one starts with an else that matches the closest and unmatched if (this principle does not apply if the closest and unmatched if is restricted to a block of code).

//Code 1
#include <stdio.h>
int main()
{
	int a = 0;
	int b = 2;
	if (a == 1)
		if (b == 2)
			printf("hehe\n");
	else
			printf("haha\n");
	return 0;
}//The result is: (Nothing output)
//Code 2
#include <stdio.h>
int main()
{
	int a = 0;
	int b = 2;
	if (a == 1)
		if (b == 2)
			printf("hehe\n");
		else
			printf("haha\n");
	return 0;
}//The result is: (Nothing output)
//Code 3
#include <stdio.h>
int main()
{
	int a = 0;
	int b = 2;
	if (a == 1)
		{
            if (b == 2)
                printf("hehe\n");
		}
		else
			printf("haha\n");
	return 0;
}//The result is: haha
//Compare codes 1, 2, 3, where both codes 1 and 2 have elses that match their nearest if. Code 3 cannot match an else outside the code block because the nearest if to else is the execution of the first if (enclosed by the code block), so it can only match the first if.

3. Code Style

To increase the readability of your code, a good code style is important.

  • In branch statements, proper use of code blocks can reduce code misunderstanding.
//Code 1
int max2 (int x, int y)
{
    if(x>y) 
        {
            return x;
        }
     return y; 
}
//Code 2
int max2 (int x, int y)
{
    if(x>y) 
        {
            return x;
        }
    else
        {
            return y; 
        }
}//Although code 1 and code 2 mean the same thing, code 1 can be easily misinterpreted. Note that once the return statement executes on behalf of the end of the function, it will not execute even if there are statements that follow.
  • If a conditional expression compares whether a variable is equal to a constant, it is always written in front to avoid missing an equal sign and causing a logical error in the code.
//Code 1
int num = 1;
if(num == 5)
{
    printf("hehe\n");
}
//Code 2
int num = 1;
if(num = 5)
{
    printf("hehe\n");
}//Leave an equal sign and the consequences are endless
//Code 3
int num = 1;
if(5 == num)
{
    printf("hehe\n");
}

switch Statements

1. Grammatical Structure

1. Structure

Switch (integer expression)

{

case  **integer constants**Expression:

			Sentence;

(break;)//Determine if you want to write a break statement

​ ......

​ (default :

Statement;) Determine whether to write default statements as needed

}

2. Examples

 int day = 0;
    switch(day)
   {
        case 1: 
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;    
        case 4:
            printf("Thursday\n");
            break;    
        case 5:
            printf("Friday\n");
            break;
        case 6:
            printf("Saturday\n");
            break;
        case 7:
            printf("Sunday\n");    
            break;
        default :
            printf("The data you entered is incorrect\n");
   }

2. Points for Attention

1. Expression requirements

  • The conditional expression that can be passed in a switch statement can only be an integer expression (char can also be used to force character data to be converted to an integer by ASCII code. Floating-point data is higher than integer level and cannot be converted to an integer, so it is not an integer expression).

  • An expression immediately following a case can only be an integer constant expression (it must be a constant, which can cause errors with the variable. It can also be a single character caused by a single quotation mark, which is converted to an integer by the ASCII code).

In a word, character types can also be considered integers in a broad sense.

//Code 1
int main()
{
	int day = 96;
	switch (day+1)
	{
	case 'a':
		printf("nice!\n");
		break;
	case 98:
		printf("Okay!\n");
		break;
	default :
		printf("Close\n");

	}
	return 0;
}
//Code 2
int main()
{
	char day = 'a';
	switch (day+1)
	{
	case 'a':
		printf("nice!\n");
		break;
	case 98:
		printf("Okay!\n");
		break;
	default :
		printf("Close\n");

	}
	return 0;
}

2. The Role of case Labels and Breaks

  • The case tag simply lets the program find the execution entry for the switch statement based on the conditional expression, and then executes the statement in sequence (if there is no break statement, the following statement will be executed even if the following case tag does not meet the criteria).

  • A switch statement cannot be branched directly, and can only be branched with a break statement. The purpose of a break is to divide the switch statement into parts and jump out of the switch statement as a switch exit.

  • The program finds the entry based on the conditional expression and the case label, and finds the switch statement exit when it encounters a break.

//Code 1
int main()
{
	int day = 96;
	switch (day+1)
	{
    case 23://Not qualified, look for the next case tag
		printf("!!!\n");
	case 'a'://Eligible, the program executes from this line down and only jumps out of the switch statement if it encounters a break
		printf("nice!\n");
	case 98://No break encountered, continue executing
		printf("Okay!\n");
		break;//When break is encountered, the switch statement is jumped out, and the statement within this switch is no longer executed
    case 33:
		printf("!!!\n");
	default :
		printf("Close\n");

	}
	return 0;//Jump here to continue
}
/*The result of execution is:
			nice!
			Okay!
*/

3. Role of default clause

  • When the value expressed does not match the value of all the case tags and you want the switch statement to give you a feedback, you can write a default clause where any case tag can appear.The statement following the default clause executes when the value of the switch expression does not match the value of all the case tags. Therefore, only one default clause can appear in each switch statement.

  • The default clause does not necessarily have to be written at the end of the statement (either at the beginning, middle or at the end), as long as the value of the switch expression does not match the value of all the case tags, the default clause can be executed.

#include <stdio.h>
int main()
{
    int n = 1;
    int m = 2;
    switch (n)//n is 1
   {
    case 1://Entry, where the program executes
            m++;//m to 3
    case 2://Last case clause has no break, continue executing down
            n++;//n becomes 2
    case 3://Last case clause has no break, continue executing down
             switch (n)//n is 2
           {//switch allows nested use
             case 1:
                    n++;
             case 2://The entry to the inner switch statement from which the program executes
                    m++;//m becomes 4
                    n++;//n becomes 3
                    break;//Jump out of the inner switch
           }
    case 4://Continue execution
            m++;//m to 5
             break;//Jump Outer break
    default:
             break;
   }
    printf("m = %d, n = %d\n", m, n);//m=5,n=3
    return 0; 
}

Posted by matbennett on Sun, 10 Oct 2021 10:15:29 -0700