简体   繁体   English

使 for 循环只运行一次的花括号?

[英]Curly braces making for loop run only once?

Let's say I have a pseudocode and sum = 3假设我有一个伪代码并且 sum = 3

for i = (1 to 3)
    sum = sum + i
    return sum

This returns 9 because 3+1=4, 4+2=6, 6+3=9这将返回 9 因为 3+1=4, 4+2=6, 6+3=9


But when doing this但是当这样做

for i = (1 to 3) {
    sum = sum + i
    return sum
}

Sum returned is 4?返回的总和是 4? Why does the curly braces somehow make the for loop run only once?为什么花括号以某种方式使 for 循环只运行一次?

If you have the following C code:如果您有以下 C 代码:

for (int i=1; i<=3; ++i)
   sum = sum + i;
   return sum;

Then you have a misleading way of writing那么你有一种误导性的写作方式

for (int i=1; i<=3; ++i)
   sum = sum + i;

return sum;

That's because the above snippets are both equivalent to the following:这是因为上面的代码段都等效于以下内容:

for (int i=1; i<=3; ++i) {
   sum = sum + i;
}

return sum;

The body of a for loop is either a single statement or a block. for循环的主体是单个语句或块。 Most languages don't consider indentation level to be significant.大多数语言不认为缩进级别很重要。 (Python is a notable exception.) (Python 是一个明显的例外。)

In contrast, the following executes the return each pass of the loop instead of after the loop is complete:相比之下,下面的代码在循环的每一次循环中执行return ,而不是在循环完成后执行:

for (int i=1; i<=3; ++i) {
   sum = sum + i;
   return sum;
}

Well, it'll never reach the second pass of the loop, of course.当然,它永远不会到达循环的第二遍。

Your indentation of the first loop is misleading.您对第一个循环的缩进具有误导性。 Unroll both and it will be apparent what's going on:展开两者,很明显发生了什么:

sum = sum + 1
sum = sum + 2
sum = sum + 3
return sum

This one adds 6 to sum and then returns it.这个把 6 加到sum然后返回它。

sum = sum + 1
return sum
sum = sum + 2
return sum
sum = sum + 3
return sum

This one adds 1 to sum and then returns it.这个将sum和加 1,然后返回它。 A return statement ends execution of the function (even if there's more statements after it, or it's inside a loop). return语句结束函数的执行(即使它后面有更多语句,或者它在循环内)。

    sum = sum + i
    return sum

run sum = sum + i 3 times.运行sum = sum + i 3 次。 Then execute return sum , cause if loop construction has no braces it will run only one next operation.然后执行return sum ,因为如果循环构造没有大括号,它将只运行一个下一个操作。

Here这里

for i = (1 to 3) {
    sum = sum + i
    return sum
}

every loop iteration will try to execute return sum and only first iteration will really execute this.每个循环迭代都会尝试执行return sum并且只有第一次迭代才会真正执行它。 Next iteraions will not be executed cause return will break the loop.下一次迭代将不会执行,因为return将打破循环。

In the second example, you are including a return statement into the body of the for loop, and thus returning on the first iteration.在第二个示例中,您将 return 语句包含在 for 循环体中,因此在第一次迭代时返回。 In the first example, only the addition/assignment statement is executed in your loop and then the result returned.在第一个示例中,仅在循环中执行加法/赋值语句,然后返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM