Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Thiago Adams Newsgroups: comp.lang.c Subject: Re: "span" Date: Fri, 22 Mar 2024 08:51:18 -0300 Organization: A noiseless patient Spider Lines: 84 Message-ID: References: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Fri, 22 Mar 2024 11:51:19 -0000 (UTC) Injection-Info: dont-email.me; posting-host="b69c71425e7b8f370ab82e463a5eae2f"; logging-data="3044519"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/TYOCD+n0d5pcfSucotKlaMobe8lO5Rek=" User-Agent: Mozilla Thunderbird Cancel-Lock: sha1:fyhWOf4RbvvJrdHU8EuQWE83wi4= In-Reply-To: Content-Language: en-US Bytes: 3377 On 22/03/2024 08:30, Stefan Ram wrote: > 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 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 > > #define SPAN_PARAM(x,a,n) x*a,size_t const n > #define SPAN(a) a,(sizeof a/sizeof 0[a]) > > void print( SPAN_PARAM( int, a, n )) > { for( size_t i = 0; i < n; ++i ) > printf( "%lld: %d\n", i, a[ i ]); } > > int main( void ) > { int a[ 3 ]={ 4, 6, 8 }; > print( SPAN(a) ); } > > . But since C is another language, there are other forces at work, > which means that the overall usability of such macros in C might not > make their definition and use worthwhile. Of course, the "smart" span > type in C++ surely can do more than my simple macros can do in C! ( C++ proposals use new type instead of qualifiers. This creates a big mess on the type system and incompatibility with C. I don't have idea how/why they do this constantly. ) C does not need this for parameters since the current array syntax already cover that. void f(int n, int a[n]) The problem is the syntax for pointers, this may be necessary in other contexts other than in parameters. C already have a syntax for pointer to array int (*)[2] p; The problem of this syntax is C code normally use pointer directly and a pointer to array requires *p everywhere. Having an specific syntax for pointer length makes the code transition from non-annotated to annotated much easier. It also avoid lots of (*p)[index] and have just p[index]. Does anyone have a suggestion for syntax to give pointers the length information? One try is int *[2] p; but the problem of this syntax is it is ambiguous with (cast) (int *[2]) //pointer to 2 ints, or pointer to array of 2 ints This alternative (int [2]*) is harder to parse since first it thinks it is array then it need fo "fix" to be a pointer.