Control loop

Choose the type of loop

Types of loops (according to the number of loops):
(1) Counting loop
(2) Continuous evaluation loop: In batch processing, the number of nodes in the queue can be judged each time to determine how many to send
(3) Infinite loop
(4) Iterative loop : Perform a loop for each element in the container

The flexibility of the loop: Is the number of loops constant or is checked every time Check
the position where the loop is executed: start, end, middle (guarantee that part of the code will definitely be executed)

1. When to use the while loop
Need a flexible loop (not sure the number of loops), or the loop needs to be executed at least once.
2. When to use the for loop. The
for loop is used in a loop with a fixed number of executions. In order to meet simple purposes, simply increment and decrement, iterate on container elements, etc.; if there is a condition that must make the execution jump out of the loop, then You should use a while loop instead.
3. When to use the loop
with exit Loop with exit: The termination condition appears in the middle of the loop, you can use while and break to simulate. Use the loop with exit to understand the code more conveniently, try to put the exit judgment conditions together. For example: Use the channel number to match and find the device in the array, and use break to exit the loop after finding it.

Loop control

What kind of error will occur in the loop: Ignoring the initialization of the accumulated variable or other loop-related variables, incorrect nesting, incorrect loop termination, ignoring or incorrectly increasing the value of the loop variable, using incorrect Loop indicator accesses array elements.
1. Enter the circulation: Guiding principle
(1) Only enter the circulation from one entrance.
(2) Put the code that initializes the loop immediately before the loop.
(3) Use while(true) for infinite loops
(4) Use for loops when appropriate: for loops concentrate the control code of the loop in one place, which helps to write a readable loop.
(5) Do not use for loops where while is more appropriate.

C中胡乱把while填充到for循环
for(rewind(InFile).RecCount = 0; !feof(InFile); RecCount++) 
{ 
	fgets(InputRec[RecCount-1], MAX_CHARS, InFile); 
} 
rewind(InFile); 
 RecCount = 0; 
 while(!feof(InFile)) 
 {
	 fgets(InputRec[RecCount], MAX_CHARS, InFile); 
	 RecCount++; 
 }

2. Handle the loop body
(1) Put the "housekeeping" work of the loop at the beginning or end of the loop. The main purpose of these statements of i++ is not to complete the loop work, but to control the loop.
(2) Like a subroutine, a loop only does one thing.
3. Exit the loop
(1) Make the loop termination condition as obvious as possible; you don't need to understand the inside of the loop to know the exit condition.
(2) Avoid the code that depends on the final value of the loop subscript, and assign this final value to a variable in an appropriate place in the loop body:

滥用循环下标的最终取值的代码:
for ( i=0; i<MaxRecords; i++ ) 
{
	if( Entry[i] = = TestValue ) 
	{
		break;
	}
} 
if( i< MaxRecords ) 
	return(TRUE); 
else 
	return(FALSE); 
修改之后的代码:
Found = FALSE; 
for(i<0; i<MaxRecords; i++) 
{ 
	if(Entry[i] == TestValue) 
	{
		Found = TRUE; 
		break;
	}
}
return(Found);

(3) Consider using a safe counter: add a variable ++ in the loop body, when this value is added to a certain degree, the code will have a problem;
4. Exit the loop early
(1) In the while loop, if you want to use a Boolean flag, The break statement should be considered.
(2) Put continue before the head of the loop to check, if it is not the value we need, we can go directly to the next loop.
(3) Be careful when using break and continue; for example: the use of locks
5. Check endpoints
(1) For a simple loop, three situations usually need to be considered: start, end, and any state in between.
(2) Efficient programmers will not only simulate in their minds, but also perform calculations manually; simulate multiple possible situations of program operation, so as to avoid problems in the later stage.
6. Use loop variables
(1) Use integers or enumerated types to represent the boundaries of arrays and loops.
(2) Use meaningful variable names in nested loops to improve readability: especially in two-dimensional and multi-dimensional arrays.
(3) Limit the scope of the loop subscript to this loop: Do not use this loop subscript outside of this loop, so as not to introduce errors with strings.
7. How long the loop should be
(1) Make the loop as short as possible, so that it can be clear at a glance
(2) Limit the nesting to more than 3 levels
(3) Move the content of the long loop to the subroutine

The loop is created from the inside out

Step 1: Identify what needs to be done in the loop

{get rate from table}
{ add rate to total}

Step 2: Convert as many comments in the loop body as possible into code

 Rate := Table[]; 
 Ttl := TtlRate+Rate ; 

Step 3: Add subscript

Rae := Table[Census.Age,Census.Sex ]; 
 TtlRate := TtlRate+Rate ;

Step 4: Increase the loop

for Person := FirstPerson to LasttPerson do 
	 begin
	 Rate := Table[Census.Age,Census.Sex] ;
	 TtlRate := TtlRate + Rate ;
 End;

Step 5: Add initialization

TtlRate := 0;
 for Person := FirstPerson to LastPerson do
 	begin
 	Rate := Table[Census[Person].Age,Census[Person].Sex] ; 
 	TtlRate:= TtlRate + Rate ; 
 end;

Key points

· The loop is complex, making it easier to read. Loops with a large amount of code are encapsulated as subroutines with no more than 3 levels of loops.
· Techniques to simplify the loop are: avoid using weird loops, minimize the number of loops, make the import and export clear, and put the housekeeping code in one place.
· The loop control variable cannot be abused. Give it a meaningful name and let it serve only one purpose.
· Carefully consider the entire cycle to ensure that the cycle can run as usual under various conditions and termination conditions.

Guess you like

Origin blog.csdn.net/weixin_37921201/article/details/88701919