Reputation: 1968
I was reading about C++ and found that array to normal non const pointer conversion ( technically called as decay) don't happen when we pass array by reference. Is there any reason behind this restriction ?
I know that in C99 there are three fundamental cases array decay happens, namely:
when it's the argument of the & (address-of) operator.
when it's the argument of the sizeof operator.
When it's a string literal of type char [N + 1] or a wide string literal of type wchar_t [N + 1] (N is the length of the string) which is used to initialize an array, as in char str[] = "foo"; or wchar_t wstr[] = L"foo";.
Furthermore, in C11, the newly introduced alignof operator doesn't let its array argument decay into a pointer either.
In C++, there are additional rules, for example, when it's passed by reference.
Thanks
Upvotes: 0
Views: 341
Reputation: 320451
Array-to-pointer decay produces an rvalue. So, for obvious reasons it only makes sense in rvalue contexts.
Reference contexts are naturally lvalue contexts, which is why array-to-pointer decay would make no sense whatsoever in such contexts.
Upvotes: 2
Reputation: 27577
The simple answer is type safety, which is one C++'s mainstays. The only reason why there's decay in some instances is C compatibility.
Upvotes: 0