sizeof(array) with variable-length array parameter

Andrew Haley
Wed Apr 9 19:18:00 GMT 2008 wrote:
> On Wed, Apr 09, 2008 at 04:51:14PM +0100, Andrew Haley wrote:
>> Well, OK, you may either do
>> int foo(int n, int p[])
>> or
>> int foo(int n, int p[])
> int bar(int n, int p[n]) I presume...


>   I am perfectly OK with sizeof returning sizeof(int*) for your
> foo() function, but it just feels so wrong to do it when the size
> is so easily accessible...

But it's *not* always easily accessible.  In this case,

int bar(int p[n])

n is somewhere in global scope, maybe in another translation unit,
and as I point out below you'd have to copy it at the time the array
was created.

>> 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.
>   Sure not, it is not changed when you do (on a 32-bit platform):
> int foo()
> { int s=10,a[s];
>   s=11;
>   assert(sizeof s==40);
> }
>   Try it... Why should the behaviour be so much different in the
> parameter passing case?

So, you're saying it *should* create a hidden copy of the size
parameter for use by sizeof?  While this would work, it's not very


More information about the Gcc-help mailing list