sizeof(array) with variable-length array parameter

Andrew Haley aph@redhat.com
Wed Apr 9 16:45:00 GMT 2008


[ x-posting removed ]

peter.kourzanov@xs4all.nl wrote:
> On Wed, Apr 09, 2008 at 01:22:15PM +0100, Andrew Haley wrote:
>> peter.kourzanov@xs4all.nl wrote:
>>> Dear gcc users and developers, 
>>>
>>>   This might be a stupid question, nevertheless...
>>>
>>>   I've been wondering for a long time, why the behaviour of
>>> variable-length arrays w.r.t. the sizeof operator is different
>>> for local/auto variables and for function arguments (in C99):
>>>
>>> #include <stdio.h>
>>> void foo(int s, int a[s]) {
>>>         printf("%u\n",sizeof a);
>>> }
>>> int main()
>>> {
>>>         int s=10,a[s];
>>>         printf("%u\n",sizeof a);
>>>         foo(sizeof a/sizeof a[0],a);
>>> }
>>>
>>>   The printf's produce very different results: the first one
>>> returns "40" the other one returns 4, implying that the compiler
>>> forgets that the size of the array is actually "s", not the size
>>> of the pointer argument. Is it so difficult to make "sizeof a" 
>>> return "s" in both cases?
>> That's C for you, I'm afraid: arrays always decay to pointers to the
>> first element when passed as arguments.  The size of a VLA is not passed.
> 
> 
>   Well, it sort of is: it is actually passed as a parameter to the
> function - look at the C99 defining a syntax for VLA parameters.

Well, OK, you may either do

int foo(int n, int p[])

or

int foo(int n, int p[])

but sizeof doesn't distinguish these two cases.  In any case, how would
you do it?  Would an assignment to n change the result of sizeof, or not?
If not, you'd have to create a "shadow" variable.

> The fact the the compiler forgets about it could be compensated by
> this...
> 
>   What I would like to know, is why the standard (ISO/IEC 9899) does
> explicitly require sizeof to return size of the pointer rather than
> more obvious response? Is it backwards compatibility? 

>   Is there any use in this behaviour besides making the life of
> the compiler development team easy?

The rationale doesn't say one way or another.

>   Surely, such an extension should be not too difficult to implement,
> provided that the compiler can account for (potential) modifications
> to the size parameter and require sizeof the return the value that
> was actually passed to the function, which BTW, it already does,
> since this behaviour is easily verified to work well for variable
> VLAs.

But that would break compliant code.  Why would you want to do that?

The fact that arrays don't have a size beyond the scope of their
declaration is an old wart in the design of C that everyone is used
to living with.

Andrew.



More information about the Gcc-help mailing list