3
for (; cnt--; dp += sz)
{
        pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
}

有人可以解释一下这个 for 循环是如何工作的吗?它属于一个cpp文件。我不明白 for 循环中的条件以及如何检查它。(正在调用该函数)

4

7 回答 7

2

语句的一般形式for如下所示:

for (init-statement; condition; expression)
    statement

init-statement用于初始化或分配在循环过程中修改的起始值。condition用作回路控制。只要condition评估为真,statement就执行。expression仅当condition为真时才对每次迭代进行评估

回到你的代码:

for (; cnt--; dp += sz)

init-statement这是一个什么都不做的空语句。conditioncnt--它评估它的值作为cntthen decrements 1。如果cnt不为零,condition则为真,如果cnt为零,condition则为假。

于 2013-09-25T06:11:45.180 回答
1

该条件被解释为真或假情景。

如果为 0,则为假,否则为真。

于 2013-09-25T06:07:37.633 回答
1

这等效于以下代码 -

for(; cnt-->0; dp += sz);

因为只要一个值不等于0,就认为是真的。

于 2013-09-25T06:12:42.843 回答
0

在 c++ 中,条件为真或假的值由非 0(真)或 0(假)确定。

只要 cnt 不为 0,上述循环就会继续迭代。当 cnt 变为 0 时,它将终止。

更新:

为了清楚这里的重要一点,终止循环的是值 0。如果由于某种原因,cnt 已经以负值开始,则循环将永远不会终止

于 2013-09-25T06:06:40.223 回答
0

请记住,普通整数也可以用作布尔值,其中零为假,非零为真。

这意味着循环将继续直到cnt为零,然后循环将结束。然而,这还不是全部,因为使用了后减运算符cnt,循环结束后的值将是-1.

于 2013-09-25T06:11:16.917 回答
0

它类似于

while(cnt--)
{
        pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
        dp += sz;
}

希望这会有所帮助。

于 2013-09-25T06:16:18.360 回答
0

所以 for 循环的语法是

 for (<initialization(optional)>; <condition(Optional)>; <increment(Optional)>)
 {
    ...
 }

说 cnt 是 2 你的循环工作如下,

  for(; cnt--; dp+=size)
  {
      ...
  }

执行流程是,

 1. initialization statement will be executed once. Since you dont have one nothing will be executed

 2. Next condition statement will be executed. In your case cnt-- which result in cnt value is considered as condition result. So, if cnt is 2 then value 2 is considered as condition result. Hence all non-zero are considered as TRUE and zero is considered as FALSE. After evaluating to TRUE it decrements cnt by 1

 3. Once the condition results in TRUE then it executes the statement part say,  pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);

 4. At the last it executes the increment statement of for loop,in you case it is dp-=size;

 5. It executes from 2 till condition evaluated to ZERO ie FALSE it comes out of loop.
于 2013-09-25T06:31:19.700 回答