Reputation: 7630
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
Upvotes: 1
Views: 192
Reputation: 279345
I think C++11 range-based for loops allow you to prevent it:
for (const int i : some_range) {
++i; // forbidden
}
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 a boost::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.
Upvotes: 1
Reputation: 7074
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.
int[] myArray = new int[100];
foreach (var item in myArray)
{
}
Upvotes: 0
Reputation: 65034
PL/SQL doesn't let you modify loop variables:
SQL> begin 2 for i in 1..10 loop 3 i := i + 1; 4 end loop; 5 end; 6 / i := i + 1; * ERROR at line 3: ORA-06550: line 3, column 5: PLS-00363: expression 'I' cannot be used as an assignment target ORA-06550: line 3, column 5: PL/SQL: Statement ignored
Upvotes: 2
Reputation: 490488
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".
Upvotes: 2
Reputation: 91119
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.
for i in range(0, 100):
print "A:", i
i += 1
print "B:", i
leads to
A: 0
B: 1
A: 1
B: 2
....
while your loop in C, provided with the correct outputs, would lead to
A: 0
B: 1
A: 2
B: 3
....
Upvotes: 1
Reputation: 7618
Not sure I fully understand your question but,
in python :
for i in range(10):
print i
i+=1 #if I print i now I will get i+1,
You will return the same result as :
for i in range(10):
print i
i.e :
0 1 2 3 4 5 6 7 8 9
Upvotes: 4