So while it is common/typical to accept an array that has decayed to a pointer like the following
#include <iostream>
void example(int* data)
{
std::cout << data[0] << ' ' << data[1] << ' ' << data[2] << std::endl;
}
int main()
{
int data[3] = {1, 2, 3};
example(data);
}
I noticed that you can also seemingly do the opposite. Namely you can pass a pointer that will undecay(?) back to an array
#include <iostream>
void example(int data[3])
{
std::cout << data[0] << ' ' << data[1] << ' ' << data[2] << std::endl;
}
int main()
{
int data[3] = {1, 2, 3};
example(data);
example(nullptr); // Is this legal? Can I prevent this?
}
Note that the data
argument of example
has changed from int*
to int[3]
yet I am still able to pass nullptr
. Changing the argument to std::array<int, 3>
will obviously prevent this, but I'm curious if this implicit conversion is described by the standard? There is a lot of commentary on "array to pointer" implicit conversion, but this seems to be the other way around.