Discussion on for cycle and foreach cycle in C

  • 2021-12-13 09:05:12
  • OfStack

In fact, for cycle and foreach cycle can be regarded as subordinate, that is, foreach cycle can be converted into for cycle, but for cycle can not be converted into foreach cycle.

The following is a brief introduction to the next two loops:

1. for cycle

Code format:

for (Expression 1; Cyclic condition; Expression 2)

{

Circulatory body

}

Code meaning:

First run Expression 1;

Then judge whether the condition is true, if it is true, execute the loop body, and then run the expression 2 after execution;

Then judge the loop condition... The loop will not end until the loop condition is false.

Precautions:

Expression 1: It can be any code, 1 will be executed and will only be executed once;

Expression 2: It can be any code that executes after the loop body executes.

2. foreach cycle

Code format:

foreach (Array or Collection of Data Type Variables in)
{
Circulatory body

}

Code meaning:

From the array or collection, take out the data of each item in turn, and assign the data to the loop variable every time. After every assignment, run the loop body once.

Precautions:

foreach loops can only be used to traverse arrays and collections;

foreach loops, also known as read-only loops, cannot change collections or arrays in the loop body;

The data type must be the same as that of every 1 item in the array or collection.

However, what are the differences, advantages and disadvantages between foreach cycle and for cycle? The following is a brief summary:

foreach Loop for Loop

Can only be used for traversal; Can be used for any form of repetitive behavior;

You cannot change the loop target; In the loop body, any operation can be performed;

Fast traversal speed and high execution efficiency. The traversal speed is slow and the execution efficiency is low.

Summary: If you need to traverse a collection or array, and you only need to read it without changing it, the foreach loop is most appropriate. Otherwise, choose other loops as needed.


Related articles: