Why doesn't C++ support range based for loop over dynamic arrays? That is, something like this:
int* array = new int[len];
for[] (int i : array) {};
I just invented the for[]
statement to rhyme with new[]
and delete[]
. As far as I understand, the runtime has the size of the array available (otherwise delete[]
could not work) so in theory, range based for loop could also be made to work. What is the reason that it's not made to work?
Unlike other high-level languages (Python, JavaScript, etc), C doesn't have built-in dynamic arrays.
Range-based for loop in C++ Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
Technically, in C it isn´t even possible to increase the size of a dynamically allocated array. In fact, realloc() does some kind of "create new object & copy the data" routine. It does not modify the size of an existant heap-memory object at all.
What is the reason that it's not made to work?
A range based loop like
for(auto a : y) {
// ...
}
is just syntactic sugar for the following expression
auto endit = std::end(y);
for(auto it = std::begin(y); it != endit; ++it) {
auto a = *it;
// ...
}
Since std::begin()
and std::end()
cannot be used with a plain pointer, this can't be applied with a pointer allocated with new[]
.
As far as I understand, the runtime has the size of the array available (otherwise
delete[]
could not work)
How delete[]
keeps track of the memory block that was allocated with new[]
(which isn't necessarily the same size as was specified by the user), is a completely different thing and the compiler most probably doesn't even know how exactly this is implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With