Iterating over 0..T.max
Magnus Lie Hetland
magnus at hetland.org
Wed Mar 9 08:09:20 PST 2011
In a (template) data structure I'm working on, I had the following thinko:
auto a = new T[n];
foreach (T i, ref e; a) {
e = i;
}
Then I instantiated it with T=bool, and n=256. Infinite loop, of course
-- the problem being that i wraps around to 0 after the last iteration.
Easily fixed, and not that much of a problem (given that I caught it)
-- I'll just use e = cast(T) i. (Of course, even with that solution,
I'd get wrap problems if n=257, but I just want to make sure I allow
T.max as a size.)
But I'm wondering: given D's excellent valua range propagations and
overflow checking, would it be possible to catch this special case
(i.e., detect when the array can be too long for the index type)? Or
are any other safeguards possible to prevent this sort of thing?
--
Magnus Lie Hetland
http://hetland.org
More information about the Digitalmars-d-learn
mailing list