Hi, new to C++. Trying to pass a const reference to an array of 4 integers.
What I've tried doesn't work :-
void Process_Input(const int []& key_states ); void Process_Input(const int key_states[]& );
At least I think that's what the compiler error is about.
void Process_Input(const int& key_states[] );
According to the compiler that's an array of references. I need a reference to an array.
I'm guessing you can't do that:
typedef int int_arr[]; void foo(int_arr& arr) { }
test.cpp:3:22: error: parameter ‘arr’ includes reference to array of unknown bound ‘int []’
Don't use C arrays in function arguments, ever. They are just a mess, and are the most broken aspect of C.
Google says this works, but I don't know:
void Process_Input(const int (&key_states)[]);
But why are you using a reference? Arrays are already passed as pointers.
A reference to an array just doesn't make sense. What are you trying to achieve?
My guess is that you want a reference to a pointer:
void Process_Input(int* &key_states);
You cannot pass a static array to that, though (since the address of an array cannot be modified, the reason why a reference to an array doesn't make sense).
[edit]
removed the 'const', it doesn't have much sense either.
void foo(const int key_states[])
gives you a reference. Though I think C/C++ specifies that this would be treated just like a pointer:
void foo(const int *key_states)
Effectively, a reference isn't much more than a const pointer that auto-dereferences when you access it. Subscripting (eg, key_states[i]) dereferences a pointer automatically, and because of an array's tendency to automatically supply a reference when not subscripted, a reference to a const integer array would be provided like this:
void foo(const int *const key_states)
Or if you want to modify the array:
void foo(int *const key_states)
Then key_states gives you the address of the array, and key_states[n] gives you the nth element of the array.
void foo(const int key_states[])
gives you a reference. Though I think C/C++ specifies that this would be treated just like a pointer:
void foo(const int *key_states)
It's not a pointer because it can't be altered, just like a reference. You could do pointer stuff to access the elements, but the memory offset of key_states[0] can't be altered in any meaningful C program.
You can't have a reference to an array, only to an array of particular size. Each array type has fixed size.
The main practical use is probably:
template <class T, unsigned N> unsigned length(const T (&)[N]) { return N; }