Sujet : Re: technology discussion → does the world need a "new" C ?
De : bc (at) *nospam* freeuk.com (Bart)
Groupes : comp.lang.cDate : 17. Jul 2024, 12:38:15
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v78af7$1qkuf$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 23
User-Agent : Mozilla Thunderbird
On 13/07/2024 10:39, BGB wrote:
But, as I see it, no real point in arguing this stuff (personally, I have better stuff to be doing...).
We all do. But this group seems to be about arguing about pointless stuff and you might come here when you want a respite from proper work.
However (here I assume you've gone back to Quake but that other interested parties might be reading this), consider the program below.
That sets up an array and then sums its elements by calling 3 different functions to do the job:
(1) Using normal C pass-by-value
(2) Using C pass-by-value to emulate call-by-reference
(3) Using fantasy true call-by-reference as it might appear if C had the
feature
(I'd hoped C++ would run this, but it didn't even like the middle function.)
I'm asking people to compare the first and third functions and their calls, and to see if there's any appreciable difference between them. There will obviously be a difference in how the A parameter is declared.
---------------------------------------------
#include <stdio.h>
typedef int T;
int sum_byvalue(T* A, int n) {
int i, sum=0;
for (i=0; i<n; ++i) sum += A[i];
return sum;
}
int sum_bymanualref(T(*A)[], int n) {
int i, sum=0;
for (i=0; i<n; ++i) sum += (*A)[i];
return sum;
}
int sum_bytrueref(T (&A)[], int n) {
int i, sum=0;
for (i=0; i<n; ++i) sum += A[i];
return sum;
}
int main(void) {
enum {N = 10};
T A[N] = {10,20,30,40,50,60,70,80,90,100};
int total=0;
total += sum_byvalue (A, N);
total += sum_bymanualref (&A, N);
total += sum_bytrueref (A, N);
printf("%d\n", total); // would show 1650
}
---------------------------------------------
Find anything? I thought not.
Those findings might suggest that C doesn't need call-by-reference, not for arrays anyway. Except that at present you can do this:
T x=42;
sum_byvalue(&x, N);
which would not be possible with call-by-reference. Nor with sum_bymanualref, but apparently nobody wants to be doing with all that extra, fiddly syntax. Better to be unsafe!