V version:V 0.1.29 ce4ee2b
OS:linux
What did you do?
I wrote the following program
for i, k in 0..5 {
print(i, k)
}
What did you expect to see?
Print the numbers from 0 to 5, or a compiler error telling me that I cannot use index, value pairs with range for loops.
What did you see instead?
==================
/tmp/v/hello.tmp.c: In function ‘main__main’:
/tmp/v/hello.tmp.c:9391:44: error: ‘i’ undeclared (first use in this function)
print(_STR("%"PRId32"\000 %"PRId32"", 2, i, k));
^
/tmp/v/hello.tmp.c:9391:44: note: each undeclared identifier is reported only once for each function it appears in
/tmp/v/hello.tmp.c: In function ‘_vinit’:
/tmp/v/hello.tmp.c:9418:38: warning: integer constant is so large that it is unsigned
_const_math__bits__max_u64 = ((u64)(18446744073709551615));
^~~~~~~~~~~~~~~~~~~~
/tmp/v/hello.tmp.c:9445:409: warning: integer constant is so large that it is unsigned
((u64)(1)), ((u64)(10)), ((u64)(100)), ((u64)(1000)), ((u64)(10000)), ((u64)(100000)), ((u64)(1000000)), ((u64)(10000000))$
((u64)(100000000)), ((u64)(1000000000)), ((u64)(10000000000)), ((u64)(100000000000)), ((u64)(1000000000000)), ((u64)(1000000$
000000)), ((u64)(100000000000000)), ((u64)(1000000000000000)), ((u64)(10000000000000000)), ((u64)(100000000000000000)), ((u64$
(1000000000000000000)), ((u64)(10000000000000000000))}));
^~~~~~~~~~~~~~~~~~~~
...
==================
(Use `v -cg` to print the entire error message)
builder error:
==================
C error. This should never happen.
If you were not working with C interop, please raise an issue on GitHub:
0..5 is a range, and only returns one value. That's why you're getting the error about i being undefined. If you want both an index and a value, do a for over an array, as shown in the docs.
The bug here is that V didn't report the problem, instead letting it fall through for C to report.
Hmm this code looks pretty reasonable -- the intent is quite clear -- and it would make sense for 0..5 to behave a lot like [0, 1, 2, 3, 4] since that is the exact range it represents.
@elimisteve This goes against the one way philosophy as you can do the same with array/slice so it should be an error IMO.
EDIT: I think it should be allowed.
0..5 is a range. It doesn't have an index or any other attribute except the numbers in the range. For example, you can't do
0..5[2]
Therefore, there is only on variable available to the for loop.
It can be implemented in the future, but for now I think a clear error message is nicer than a C compilation error.
Yeah, this was not really a "request" for this kind of thing. I was just playing around with the language and realized that this produced a C compilation error, which shouldn't be the case. Thanks for fixing it so quickly.
Most helpful comment
0..5is a range. It doesn't have an index or any other attribute except the numbers in the range. For example, you can't doTherefore, there is only on variable available to the
forloop.