In the following code, I have tried using a field variable (of class or record) or an array element directly as a loop counter, but this was illegal ("error: invalid index expression"). Is this simply because the loop counter must be a scalar variable?
class Cls {
var n: int;
}
proc main()
{
var x = new Cls( 100 );
var k: [1..10] int;
for x.n in 1..3 do // error: invalid index expression
writeln( x.n );
for k[1] in 1..3 do // error: invalid index expression
writeln( k[1] );
}
On the other hand, if I create a reference to x.n
, it compiled successfully but x
in the outer scope was not modified. Is this because a new loop variable named n
is created in the for-loop? (which I'm afraid is almost the same as my another question...)
proc main()
{
var x = new Cls( 100 );
ref n = x.n;
for n in 1..3 do
writeln( n );
writeln( "x = ", x ); // x = {n = 100}
}
If a loop variable is created independently, I guess something like "var x.n = ..." might happen (internally) if I write for x.n in 1..3
, which seems really invalid (because it means that I'm trying to declare a loop variable with a name x.n
).