Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C++ support range based for loop for dynamic arrays?

Tags:

c++

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?

like image 938
Balint Laczay Avatar asked Nov 18 '17 07:11

Balint Laczay


People also ask

Does C support dynamic arrays?

Unlike other high-level languages (Python, JavaScript, etc), C doesn't have built-in dynamic arrays.

Does C have range based for loops?

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.

Can I increase the size of dynamically allocated array in C?

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.


1 Answers

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.

like image 185
user0042 Avatar answered Oct 18 '22 12:10

user0042