Re: Array Size : Error : Why ??
Am 09.11.2011 21:20, schrieb Vipin:
I am seeing the following as an error by compiler. I remember it
should be an error but want to know the concept behind it.
To make the problem statement more clear, I deliberately simplified your
example to
int Data[] = {0};
int main (){
sizeof Data/sizeof Data[0];
sizeof (int [])(&(Data[0]))/ sizeof Data[0];
}
The question is: Why is the second statement in main ill-formed?
The reason is some curiosity of the C++ language related to incomplete
types. To determine the size of some object or type, sizeof needs a
complete type. E.g. if you declare (but do not define=
class X;
the expression sizeof(X) is ill-formed, because the type X has not been
completely defined yet, so quiring sizeof cannot succeed.
We have a similar situation for a declaration of an array type without
bounds, like 'int[]'. Therefore testing the expression
sizeof(int[])
is also ill-formed, because sizeof has no information about the array
length.
The special situation is, when we have an array definition of the form
int Data[] = {0};
Here, the type of Data is incomplete until the closing brace, but after
the closing brace it is complete and has type int[1], because there is a
single element initializer.
Now writing a casting expression of the form
(int [])(&(Data[0])
is ill-formed for several reasons:
a) You cannot cast to an incomplete type
b) Even if we would write
(int[1])(&(Data[0]))
instead, this won't work, because arrays immediately undergo
array-to-pointer conversion unless directly bound to a reference to
array. The question anyway is, *why* you want to perform this code
transformation?
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]