问题描述
for(int i = 0; i< c)在C ++中,允许更改for循环内的循环变量: ; limit; i ++){
if(condition){
i--;
$ b现在如果一个循环体是相当复杂的,立即对读者显而易见的是,循环变量 在循环体内 是否被改变。这样可以很好地调整代码,这样一旦读者只看到for循环的头部,他就会立即知道循环变量在body 中没有被改变。
例如,如果我使用 const
:
const int value = computeValue();
//这里有很多代码
然后很清楚的是, const
变量定义该变量是不变的。
有没有办法实现类似的东西 - 迭代中的逻辑常量 - 在C ++中的for循环控制变量?
,但我想这可以被认为是一个额外的理由,鼓励使用和以反复执行STL容器。
编辑 ...和C ++ 0x (感谢Matthieu。M:)
In C++ changing a loop variable inside a for-loop is allowed:
for( int i = 0; i < limit; i++ ) {
if( condition ) {
i--;
}
}
Now if a loop body is rather complex it is not immediately obvious to the reader whether the loop variable is changed inside the loop body. It would be nice to somehow tweak the code so that once the reader only sees the for-loop header he immediately knows that the loop variable is not changed inside the body.
For example, if I use const
:
const int value = computeValue();
//lots of code here
then it is clear that whatever code is written below the const
variable definition the variable is unchanged.
Is there a way to achieve something similar - logical constness within the iteration - in case of for-loop control variables in C++?
解决方案 I don't think this is possible for hand-crafted loop, but I'd guess that could be considered an additional argument to encourage the use of std::for_each and BOOST_FOREACH for iterations over STL container.
EDIT ... and the C++0x range-based for-loop (thanks Matthieu. M :)
这篇关于如何显示循环控制变量在C ++ for-loop内部没有改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!