增加 for 循环计数器的值
是否有任何编程语言/脚本不允许增加循环内 FOR 循环的计数器?
例如:
for(int i = 0; i < 10; i++)
{
i++;
print i
}
Output: 1 3 5 7 8 9
Is there any programming language/script who won't allow increasing the counter for an FOR loop inside the loop?
For example:
for(int i = 0; i < 10; i++)
{
i++;
print i
}
Output: 1 3 5 7 8 9
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不确定我完全理解你的问题,但是,
在 python 中:
你将返回与以下相同的结果:
即:
Not sure I fully understand your question but,
in python :
You will return the same result as :
i.e :
Pascal(举一个例子)基本上说,更改循环中的变量会产生未定义的行为(Pascal 用户手册,§C.3):“控制变量、初始值和最终值必须具有相同的标量类型(不包括类型 real),并且不能被 for 语句更改。”
IIRC,Ada 确实阻止您进行此类修改。看看圣经似乎证实了我彻底虚弱的记忆(Ada 95 RM,§5.5(10)):“循环参数是一个常量;它不能在循环的sequence_of_statements内更新”。
Pascal (for one example) basically said changing the variable in the loop gave undefined behavior (Pascal User Manual, §C.3): "The control variable, the initial value, and the final value must be of the same scalar type (excluding type real), and must not be altered by the for statement."
IIRC, Ada does prevent you from making such modifications. Looking at the bible seems to confirm my thoroughly infirm memory (Ada 95 RM, §5.5(10)): "A loop parameter is a constant; it cannot be updated within the sequence_of_statements of the loop".
PL/SQL 不允许修改循环变量:
PL/SQL doesn't let you modify loop variables:
我不知道有任何语言明确禁止它。但对于其后果有不同的概念。
变量,如 C 中的变量
在 C 中,这个循环导致有效地生成 2 步,这是显而易见的。
迭代器,就像 Python 中的那样
在 Python 中,这样的循环由迭代器提供,迭代器不断地产生独立于变量的新值。
导致
<前><代码>A:0
乙:1
答:1
乙:2
....
当你的 C 循环提供正确的输出时,会导致
<前><代码>A:0
乙:1
答:2
乙:3
....
I don't know of any language explicitly forbidding it. But there are different concepts of what consequences it has.
Variable, like in C
In C, this loop leads to effectively making steps of 2, as obvious.
Iterator, like in Python
In Python, a loop like this gets fed by an iterator which constantly yields new values independent of the variable.
leads to
while your loop in C, provided with the correct outputs, would lead to
我认为 C++11 基于范围的 for 循环允许您阻止它:
但我不认为该标准提供了一种简单的方法来定义整数范围,如正常的
for
循环。some_range
可以是一个容器,或者一个boost::counting_range
。您是否认为这是“FOR 循环的计数器”取决于您。我想一个“正确的”示例是一个循环,它采用任意表达式来修改循环之间的计数器(示例中的
i++
),但不允许在其他循环中修改计数器比那个表达。I think C++11 range-based for loops allow you to prevent it:
But I don't think the standard provides a simple way to define an integer range as in the normal
for
loop.some_range
could be a container, or aboost::counting_range
.Whether you consider this "the counter for a FOR loop" is up to you. I suppose a "proper" example would be a loop that takes an arbitrary expression to modify the counter between loops (
i++
in your example), but doesn't allow the counter to be modified in the loop other than by that expression.据我所知没有。但是,在 C# 中,您可以为每个执行 a 操作,如果集合发生更改,它将引发异常。
Not that I know of. However, in C# you can do a for each and it will throw an exception if the collection is changed.