for (; cnt--; dp += sz)
{
pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
}
有人可以解释这个for循环是如何工作的吗?它属于cpp文件。 我不理解for循环中的条件以及如何检查它。 (正在调用该函数)
答案 0 :(得分:2)
for
语句的一般形式如下所示:
for (init-statement; condition; expression)
statement
init-statement
用于初始化或分配在循环过程中修改的起始值。 condition
用作循环控件。只要condition
的计算结果为true,就会执行statement
。仅当expression
为真时才会对每次迭代计算condition
返回您的代码:
for (; cnt--; dp += sz)
init-statement
这里是一个无效的空语句。 condition
为cnt--
,其值为cnt
,然后递减1
。如果cnt
为非零,则condition
为真,如果cnt
为零,则condition
为false。
答案 1 :(得分:1)
该情况被解释为真或假的情况。
如果它为0,那么它将为假,否则为真。
答案 2 :(得分:1)
这相当于以下代码 -
for(; cnt-->0; dp += sz);
因为只要值不等于0,就认为是真的。
答案 3 :(得分:0)
在c ++中,条件为true或false的值由非0(true)或0(false)确定。
只要cnt不为0,上述循环就会继续迭代。当cnt变为0时,它将终止。
更新:
为了清除这里的重点,终止循环的是值0。如果由于某种原因, cnt已经以负值开头,则循环将永远不会终止
答案 4 :(得分:0)
请记住,普通整数也可以用作布尔值,其中零为假,一切非零都为真。
这意味着循环将持续到cnt
为零,然后循环结束。然而,这不是整个故事,因为在循环结束后使用后递减运算符cnt
的值将为-1
。
答案 5 :(得分:0)
类似于
while(cnt--)
{
pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
dp += sz;
}
希望这有用。
答案 6 :(得分: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.