Liste des Groupes | Revenir à cl c |
On Wed, 17 Jul 2024 12:38:15 +0100As written, the function's parameters match arrays of any size, with the length passed separately.
Bart <bc@freeuk.com> wrote:
On 13/07/2024 10:39, BGB wrote:The C++ syntax your are looking for is sum_bytrueref(std::array<T,10>&A,
>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!
And indeed, the generated code is the same.Is it? Then that's not what I want; this not about emulating value arrays.
https://godbolt.org/z/dYGoWsdjE
But why is it the same? Because in C++ arrays are also 2nd class
citizen, like in C ! std::array is not a 'native' C++ type, but a
wrapper around array-within-struct pattern.
The proper comparison would be vs language that has arrays as 1st classThat is not neccessary here, since I'm trying to show that there is little difference in the calling code and the function body between the idiomatic C code for passing arrays, and what would be used with true pass-by-reference.
citizen.
Les messages affichés proviennent d'usenet.