Hello Guys,
why array of references are not allowed,can anyone give me explanation on this.
thanks in advance
Printable View
Hello Guys,
why array of references are not allowed,can anyone give me explanation on this.
thanks in advance
Because the standard does not require a reference to have a size in memory, and array elements must have a defined size.
In practice most compilers implement references as pointers, which have a size, but there are other possibilities.
I have a sample program created for array of references, it works fine.
void main()
{
cout << endl << endl << "Values in nArray2 when referenced" << endl;
int pnArray2[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int (&array_ref)[ 10 ] = pnArray2;
for(int i=0;i < 10; i++)
{
cout << array_ref[i] << endl;
}
}
Some compilers support other things that are not in the standard, GNU seems to allow arrays of references. Another example of compiler specific functionality is your main method. G++ wont compile unless main returns int.
Looks like an array of ints to me, not an array of references. What happens if you try to make an array of references to ints, like this?
Code:&int pnArray2[10];
That's int main() ! :mad:
Yes. The correct syntax to incorectly create an array of references is:
Both of which are diagnosed as:Code:int &(array_ref[10]) = ...;
or
int &array_ref[10] = ...;
Code:error: declaration of 'array_ref' as array of references
When was the last time you coded an array declared like that, with all of those parentheses? Probably never. Wouldn't this be much easier?
But this doesn't compile, so this means that there is no such thing as an "array of references". This is from the on-line Comeau compiler:Code:int &array_ref[10];
Your original declaration is not an "array of references". It is a single reference to an array of 10 integers. If you tried to assign an array with a different number of ints, you get an error.Code:Thank you for testing your code with Comeau C/C++!
Tell others about http://www.comeaucomputing.com/tryitout !
Your Comeau C/C++ test results are as follows:
Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing. All rights reserved.
MODE:strict errors C++ C++0x_extensions
"ComeauTest.c", line 12: error: array of reference is not allowed
int &array_ref[ 10 ] = pnArray2;
Regards,
Paul McKenzie