【问题标题】:What does I_n_test = I_N mean inside of the for loop? [duplicate]I_n_test = I_N 在 for 循环中是什么意思? [复制]
【发布时间】:2020-09-28 07:24:12
【问题描述】:

我正在尝试理解这里的代码:http://devernay.free.fr/vision/src/prosac.c

主要是我想把它翻译成python。

这是一个sn-p:

for(n_test = N, I_n_test = I_N; n_test > m; n_test--) { 
  // Loop invariants:
  // - I_n_test is the number of inliers for the n_test first correspondences
  // - n_best is the value between n_test+1 and N that maximizes the ratio                       
  I_n_best/n_best
  assert(n_test >= I_n_test);
  ...
  ...
  // prepare for next loop iteration
  I_n_test -= isInlier[n_test-1];
} // for(n_test ...

那么 I_n_test = I_N; 在循环语句中做了什么?

这是一个停止条件吗?那不应该是"=="吗?

【问题讨论】:

  • 停止条件是n_test > m不再成立。
  • 语法不应该是 "==" 吗?
  • @als7 不,这是一项任务。 = 是合适的。仔细阅读答案。

标签: c loops for-loop syntax


【解决方案1】:

你可以阅读

 for(n_test = N, I_n_test = I_N; n_test > m; n_test--)

作为

 for (initialization ; loop-checking condition; increment/decrement)

来自规范,章节§6.8.5.3C11

声明

  for ( clause-1 ; expression-2 ; expression-3 ) statement

的行为如下: 表达式 expression-2 是控制表达式 在每次执行循环体之前进行评估。表达式expression-3 是 在每次执行循环体后评估为 void 表达式。如果clause-1 是 声明,它声明的任何标识符的范围是声明的其余部分,并且 整个循环,包括其他两个表达式;按执行顺序到达 在控制表达式的第一次评估之前。如果clause-1 是一个表达式,它是 在控制表达式的第一次评估之前评估为 void 表达式。

因此,按照语法,n_test = N, I_n_test = I_N 是包含初始化语句的表达式。它们由comma operator分隔。

【讨论】:

  • 但是它有什么作用呢? I_n_test = I_N,只是一个作业?
  • @als7 是的,没错。
  • 所以如果你把它放在循环之外,效果会一样吗?
  • 在这种情况下,是的。
【解决方案2】:

它 (I_n_test = I_N;) 是停止条件吗?

不,这不是条件的一部分。

那不应该是"=="吗?

不,= 完全合适。

"那么I_n_test = I_N; 在循环语句中做了什么?"

I_n_test = I_N 只是变量I_n_test 的初始化/赋值,因为它是for 循环头的三个部分中的第一个 部分,由; 分隔。

这是一个展开的语法介绍:

for (
      initializations (optional)  
      ;
      condition (obliged if it shouldn't be an endless loop)  
      ;
      in- and/or decrementation (optional if the condition can be influenced 
    )                           inside the loop´s body or as side effect of 
                                the condition itself) 

由于有两个初始化,所以需要在第一节中用, 逗号运算符将它们分开。否则会是语法错误。

要了解有关逗号运算符的更多信息,请查看:

What does the comma operator , do?


由于n_testI_n_test都是在循环之前声明的,

for (n_test = N, I_n_test = I_N; n_test > m; n_test--) { ... 

基本上相当于:

n_test = N;
I_n_test = I_N;

for (; n_test > m; n_test--) { ...

但赋值被带入循环头以表明变量n_testI_n_test 在循环上下文中至少有一个主要用途。

【讨论】:

  • 哦,好吧,这很有意义!最后一部分为我清除了它!
【解决方案3】:

for(n_test = N, I_n_test = I_N; n_test > m; n_test--)

它初始化 I_n_test = I_N & n_test = N 并且两个变量必须用“,”而不是“;”分隔. 如果用分号分隔,则编译器将 I_n_test = I_n 视为条件而不是初始化,即使您初始化了 I_n_test = I_n。 所以它就像循环内的变量赋值一样工作。

【讨论】:

    猜你喜欢
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2011-08-06
    相关资源
    最近更新 更多