Re: why cant functions return arrays
- From: "Bartc" <bc@xxxxxxxxxx>
- Date: Mon, 14 Apr 2008 23:55:07 GMT
"Hallvard B Furuseth" <h.b.furuseth@xxxxxxxxxxx> wrote in message
news:hbf.20080415l0zd@xxxxxxxxxxxxxxxx
sanjay.vasudevan@xxxxxxxxx writes:
Why are the following declarations invalid in C?
int f()[];
int f()[10];
Probably because of the language (mis)feature that array expressions
often decay to pointers to the first element of the array.
What would you do with that function? The 2nd variant:
int a[10] = f();
would presumably be a case of assigning the contents of an array to
another array, which C does not support. This won't compile either:
int a[10], b[10];
void foo() { a = b; }
Or if you would do this:
foo() { int *a; ... { ... a = f(); ... } }
then there is still an array-to-array assignment going on, only this
time to a temporary variable on the stack. However in this case it's
worse: The compiler may not be able to tell when the temporary becomes
"dead" so the space can be reused. It'd have to keep it around until
the function returns. This is because it created a pointer to the
temporary, which it won't do with other kinds of temporaries.
*a is a pointer to int. f() returns an array of int. So there is a type
mismatch and this should not compile, and the problem would not arise. I
don't think you can reasonably expect an array returned by a function to
'decay' to a pointer in the same way as a normal array.
(Creating a pointer to a value returned by a function is not a good idea
anyway, array or not)
--
Bart
.
- Follow-Ups:
- Re: why cant functions return arrays
- From: Hallvard B Furuseth
- Re: why cant functions return arrays
- References:
- why cant functions return arrays
- From: sanjay.vasudevan@xxxxxxxxx
- Re: why cant functions return arrays
- From: Hallvard B Furuseth
- why cant functions return arrays
- Prev by Date: Re: How to design a program in C?
- Next by Date: Re: How do I create a function in my library for passing user callback function
- Previous by thread: Re: why cant functions return arrays
- Next by thread: Re: why cant functions return arrays
- Index(es):
Relevant Pages
|