cpp_is_king said:
What the fuck... I just... I don't even know what to say
Father_Mike said:
Unless you're working in very low level code, there are few reasons to use raw arrays in C++. They come with a bunch of gotchas, and are generally a pain to work with.
1. std::vector is often equally efficient, and provides much a simpler interface. It's easier to pass between functions, and provides fewer surprises. If you really do need behaviour more similar to a raw c-array, you can then use raw arrays, or templated versions which compile into identical code, but come with some helpful functionality, such as the length of the array built directly into the type.
2. On the occasions you need a multidimensional array, boost::multi_array provides similar benefits for +2D arrays.
3. A templated multidimensional array also solves the problem that functions must specify the dimensions of array they take (aside from the last dimension). They require that to compute the index. A templated array handles this nicely, removing that requirement if you so choose.
4. Using array notation to pass arrays between functions results in oddities. Arrays decay to pointers when you pass them between functions, so you might as well allow the code to reflect the actual state of the data structure. To do otherwise means someone is eventually going to be confused by this:
Code:
#include <iostream>
void function(int array[], int numElements)
{
std::cout << "Now size is: " << sizeof(array) << endl;
}
void main()
{
int array[5];
std::cout << "Size is: " << sizeof(array) << endl;
function(array, 5);
}
Code:
Output:
Size is: 20
Now size is: 4
Behavior is more sensible using pointer notation:
Code:
void function(int* array, int numElements)
{
std::cout << "Now size is: " << sizeof(array) << endl;
}
Now it's clear why it prints 4.
If you'd like to explain why you should use raw arrays whenever possible, use array notation when passing raw arrays into functions, or use 2D arrays instead of simple template classes that compile into nearly identical code, I'd love to hear it.