Sujet : Re: technology discussion → does the world need a "new" C ?
De : bc (at) *nospam* freeuk.com (bart)
Groupes : comp.lang.cDate : 10. Jul 2024, 01:38:23
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v6kl5v$1j8l7$1@dont-email.me>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
User-Agent : Mozilla Thunderbird
On 10/07/2024 00:50, Keith Thompson wrote:
bart <bc@freeuk.com> writes:
[...]
Arrays can be passed by explicit reference:
>
void F(int(*A)[20]) {
printf("%zu\n", sizeof(*A)/sizeof((*A)[0])); // shows 20
}
>
That can be called like this:
>
int a[20];
F(&a);
On the language level, that's passing a pointer to an array object.
The pointer itself is passed by value. Passing a pointer to an array
is conceptually no different than passing a pointer to anything else.
I was replying to:
"In C, arrays are not passed to functions, period."
C has pass-by-reference in exactly the same way that it has
linked lists. It has neither as a language feature, but both can
be emulated using pointers. And you can't really understand how
C handles arrays if you start by asserting that they're "passed
by reference".
This is how I can pass arrays by reference in my language:
proc F([]int &A) =
A[2]:=777
end
proc main=
static[]int A = (10,20,30)
println A[2] # shows 20
F(A)
println A[2] # shows 777
end
Without the feature I'd need to use 'ref[]int A' and call as F(&A) (the extra deref inside F is added by the commpiler).
This is how you might do the same thing in C:
void F(int A[]) {
A[1]=777;
}
int main(void) {
int A[] = {10,20,30};
printf("%d\n", A[1]); // shows 20
F(A);
printf("%d\n", A[1]); // shows 777
}
To get the 777 output involves somehow passing the array by reference.
But notice how C gives exactly the same result as my code that used by-reference, even though:
* C "doesn't pass arrays by reference"
* C's F function uses the same parameter type (only & is missing; maybe
by-ref is implicit...)
* No explicit de-ref is needed inside F
* No explicit address-of is needed when calling F
So C behaves exactly as though it passes arrays by-reference, and yet it doesn't have pass-by-reference. In fact, C does it without even needing to be told!