Sujet : Re: "span"
De : ben.usenet (at) *nospam* bsb.me.uk (Ben Bacarisse)
Groupes : comp.lang.cDate : 23. Mar 2024, 01:17:11
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <87edc1iyyg.fsf@bsb.me.uk>
References : 1
User-Agent : Gnus/5.13 (Gnus v5.13)
ram@zedat.fu-berlin.de (Stefan Ram) writes:
Some people suggested to introduce a feature "span" (probably a
type) into C++, so that when one has an int array "a" and calls
"f( a )", the length of a is being transferred to "f", which "f"
is defined using "void f(span<int> a)". The "span" in "f" then
knows the length of "a". This is supposed to be less error prone
than passing a pointer with a separate length argument.
>
Of course, I immediately wondered whether one could implement
such a "span" for C, and here's a draft:
>
#include <stdio.h>
>
#define SPAN_PARAM(x,a,n) x*a,size_t const n
#define SPAN(a) a,(sizeof a/sizeof 0[a])
The usual reason given for writing 0[a] in a macro is so that
parentheses are not needed as they would be (recommended) for *(a) or
(a)[0]. But since you don't seem to care about writing a rather than
(a) I don't see why you wrote 0[a] rather than either *a or a[0].
void print( SPAN_PARAM( int, a, n ))
{ for( size_t i = 0; i < n; ++i )
printf( "%lld: %d\n", i, a[ i ]); }
What happens when print wants to pass 'a' to another function that takes
a span?
int main( void )
{ int a[ 3 ]={ 4, 6, 8 };
print( SPAN(a) ); }
-- Ben.