In C++, the poisition of const has special rules with/without the pointer is present.
Let's first see some examples that shows that the position of the const is irrelevant in terms of reference or ordinal Type declaration without pointer.
let 's see the example :
suppose we have function template, which is as follow.
int main3(int argc, _TCHAR* argv[]) { // it does not matter if you have int const or const int const int c_a = 0; int const c_a2 = 0; // nor does it matter if you have const int & or int const & const int &r_ca = c_a; int const &r_ca2 = c_a; // the thing that get tricker is when the pointer is involved // ponter to array int *p_ia = ia; // point to const array const int *p_cia = ia; // reference to pointer to const array const int *&r_cia = p_cia; // reference to pointer to const array int const *&r_cia2 = p_cia; // const reference to pointer to array int * const &r_cia3 = p_ia; //int * &const r_cia4 = p_ia; // this is a compilation warning, chronical use error, wrong qualification // const reference to pointer to const array const int * const & r_cia4 = p_cia; // you cannot change the value of r_cia3 and r_cia4 //r_cia3 = 0; // error: you cannot assign to const //r_cia4 = 0; // error: you cannot assign to const return 0; }
So as you can see, it does not matter if you have int const of const int, nor does it matter if you have const int & or int const &;
Given the following function template definition;
template<typename Type, int size> Type min(Type (&r_arr)[size]) { Type min_val = r_arr[0]; for (int i = 1; i < size; i++) { if (r_arr[i] < min_val) { min_val = r_arr[i]; } } return min_val; }
Suppose that you want to manifest that there is no change to the array and the return value is a rvalue, then you can add the const modifier
template<typename Type, int size> const Type min(const Type (&r_arr)[size]) { Type min_val = r_arr[0]; for (int i = 1; i < size; i++) { if (r_arr[i] < min_val) { min_val = r_arr[i]; } } return min_val; }
but some readers may wonder what if I add in addition a reference symbols, such as this:
template<typename Type, int size> const Type& min(const Type& (&r_arr)[size]) { Type min_val = r_arr[0]; for (int i = 1; i < size; i++) { if (r_arr[i] < min_val) { min_val = r_arr[i]; } } return min_val; }
It won't compile as the error:
"r_arr: reference to reference is illegal"
"r_arr: array of reference is illegal"
as many user may have found out, as it does not make difference to have "const Type &" or "Type const &", so the following declaration is also wrong.
template<typename Type, int size> Type const& min(Type const& (&r_arr)[size]) { // ... }