Why you cannot return fixed size / const array in C? -
i wonder why not possible return array in c? after all, array pointer backed size info (to make sizeof
work). first thought done prevent me returning array defined on stack, nothing prevents me returning pointer on stack (gcc warns me, code compiles). , can return string literal statically storaged array of chars. way, in lunux stored in .rodata
, , const array stored there (check objdump
), can return array (casting pointer) , works, afaik implementation-specific (another os/compiler may store const on stack).
i have 2 ideas how implement array returning: copy value (as done structure. can return array wrapping structure!!), , create pointer automatically or allow user return const array , create contract such array should have static storage duration (as done strings). both ideas trivial! so, question why k&r did not implement that?
an array not "just pointer backed size info".
an array block of contiguous elements of type. there no pointer.
since array object, pointer can formed points array, or 1 of array's elements. such pointer not part of array , not stored array. make sense "an int
pointer backed size of 1
int".
the size of array known compiler in same way size of object known. if have double d;
known sizeof d
sizeof(double)
because compiler remembers d
object of type double
.
nothing prevents me returning pointer on stack
the c standard prevents doing (and using returned pointer). if write code violates standard on own.
and can return string literal
a string literal array of char. when use array in return statement, converted pointer first element.
to enable arrays returned (and assigned) value, rule regarding conversion of array pointer (sometimes called "decay") have changed. possible, k&r decided make decay ubiquitous when designing c.
in fact possible have language c without having decay @ all. maybe in hindsight have saved lot of confusion. chose implement c in way did.
in k&r c, not possible return structures value either. copy operation not primitive type, had done memcpy
or equivalent iterative copy. seems reasonable design decision given way hardware resources in 1970s.
ansi c added possibility return structures value , have been late change decay rule if had wanted to; break lot of existing code relying on decay rule.
Comments
Post a Comment