C language - how to break out of multi-level loops

We know that the break statement in C language can only jump out of the nearest loop, but sometimes we need to jump out of multiple loops.
What should we do?

1. goto statement

 As shown in the figure, we can add a flag after the loop that needs to be jumped out, and add a goto statement when the conditions are met, so that the entire loop can be jumped out directly when the conditions are met.

We have also introduced the use of goto statements before.

2. Modify the outer loop conditions

for (int i = 0; i < MAX1; i++)
	{
		for (int j = 0; j < MAX2; j++)
		{
			if (condition)
			{
				i = MAX1;
				break;
			}
		}
	}

As above, when the conditions for jumping out of the loop are met, we can jump out of the multi-layer loop in the inner loop so that the variables controlling the outer loop cannot meet the loop conditions.

3. Set judgment conditions in the outer loop

for (; symbol != 1 && condition2; )
{
	for (; symbol != 1 && condition3; )
	{
		if (condition1)
			symbol = 1;
	}
}

As above, we have added a second judgment variable in the loop conditions of multiple loops. When the conditions for jumping out of the loop are met, the value of this variable is modified so that it cannot satisfy the loop conditions, and then the multi-level loops are jumped out.

4. Add break after the outer loop

for (; condition2; )
	{
		for (; condition3; )
		{
			if (condition1)
				symbol = 1;
		} 
		if (symbol == 1)
			break;
	}

As above, add a break statement in the outer loop.

Guess you like

Origin blog.csdn.net/m0_75186846/article/details/132332950