C language - break statement and return statement_study notes

break statement

The function of break statement

The break statement is a flow control statement that is used to jump out of the current execution flow in a loop structure or switch statement. Can be used in for, while, do-while and other loop structures.

In a loop structure, when the program reaches the break statement, it will immediately jump out of the current loop and continue executing the next statement.

In the switch statement, when the program reaches the break statement, it will immediately jump out of the current switch statement and continue executing the next statement.

Things to note when using the break statement

  1. The break statement can only be used within a loop body, not within a function body.
  2. The break statement can only jump out of the current loop body and cannot jump out of other functions or statement blocks.
  3. When using break in a nested loop, you need to pay attention to which loop body is jumped out.
  4. Try to avoid using too many break statements in the loop body, otherwise it will affect the readability and efficiency of the program.

return statement

The function of return statement

The return statement is used to return a value from a function. When the program executes the return statement, it will immediately end the execution of the current function and return the value after the return statement to the caller.

The value after the return statement can be any type of data, including basic data types, structures, pointers, etc.

Things to note when using return statements

  1. return can only be written inside the function body. If it is written outside the function body, an error will be reported.
  2. The official definition is that return can be followed by a value, which means it can be followed by any data type, number, string, object, etc.
  3. return can break out of the loop. Therefore, return is often used to terminate the entire function. Break is used to terminate loops and switches.

Example

break statement

#include <stdio.h>

int main() {
    
    
	int i;
	for (i = 1; i <= 10; i++) {
    
    
		if (i == 5) {
    
    
			break;
		}
		printf("%d\n", i);
	}
	printf("程序结束!!");
	return 0;
}

Insert image description here

return statement

#include <stdio.h>
int main() {
    
    
	int i;
	for (i = 1; i <= 10; i++) {
    
    
		if (i == 5) {
    
    
			return;
		}
		printf("%d\n", i);
	}
	printf("程序结束!!");
	return 0;
}

Insert image description here

Guess you like

Origin blog.csdn.net/yjagks/article/details/132117940