extern char *foo vs. extern char foo[]

Karl Heuer karl at haddock.ima.isc.com
Tue Jun 5 09:37:19 AEST 1990


In article <6263 at wolfen.cc.uow.oz> pejn at wolfen.UUCP (Paul Nulsen) writes:
>The confusion over the difference between char * and char [] is very common.
>I believe that it is due to the way that C handles the passing of array
>arguments to functions. As rule C passes arguments by value, but it passes
>an array argument by reference.

Actually, function arguments in C are *always* passed by value, but sometimes
the value in question is a pointer, which can give the same result as a call
by reference.  Thus `void f(int *pi); ... f(&i);' can be considered either a
pointer-to-int passed by value, or an int passed by reference.

In the case of an array, strictly speaking, a true call by reference in this
sense would be `void f(int (*pa)[N]); ... f(&a);', where the user explicitly
passes the address of the array (and the caller expects it).  The more common
usage `void f(int *pi); ... f(a);' is not an array passed by reference.  Also,
this effect is not in any way an exception to the usual rules.  In *any*
rvalue context, an array-valued expression `a' decays into the pointer-valued
expression `&a[0]'.

The wart in the language is not that `arrays are passed by reference and
scalars are passed by value', but rather that, in the one special case of
declaring a formal parameter to a function, the language permits the user to
write a pointer declaration using brackets instead of an asterisk.  This
often misleads people into believing that they've declared an array, when in
fact they've declared a pointer.  This is probably the cause of the original
confusion in this thread.

Karl W. Z. Heuer (karl at ima.ima.isc.com or harvard!ima!karl), The Walking Lint



More information about the Comp.lang.c mailing list