Re: "span"

Liste des GroupesRevenir à cl c  
Sujet : Re: "span"
De : 433-929-6894 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.c
Date : 23. Mar 2024, 03:11:28
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20240322173153.95@kylheku.com>
References : 1 2
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2024-03-23, Ben Bacarisse <ben.usenet@bsb.me.uk> wrote:
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?

How about linking the names of a and the size, like a and a_n?
Then we can make sure there is a _n size, whether we have an
array or pointer:

  #include <stddef.h>
  #include <stdio.h>

  #define SPAN_DEF(type, a, size, init)                 \
    type a[size] = init; const size_t a ## _n = size

  #define SPAN_PARAM(type, a)                           \
    type *a, size_t const a ## _n

  #define SPAN(a) a, a ## _n

  void print(SPAN_PARAM(int, a))
  {
    for (size_t i = 0; i < a_n; i++)
      printf("%zd, %d\n", i, a[i]);
  }

  void print_wrap(SPAN_PARAM(int, a))
  {
    print(SPAN(a));
  }

  int main(void)
  {
    SPAN_DEF(int, a, 42, { 0 });
    print_wrap(SPAN(a));
  }

--
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal
Mastodon: @Kazinator@mstdn.ca

Date Sujet#  Auteur
22 Mar 24 * "span"13Stefan Ram
22 Mar 24 +* Re: "span"8Thiago Adams
23 Mar 24 i`* Re: "span"7Ben Bacarisse
23 Mar 24 i `* Re: "span"6Thiago Adams
23 Mar 24 i  `* Re: "span"5Keith Thompson
24 Mar 24 i   `* Re: "span"4Ben Bacarisse
24 Mar 24 i    `* Re: "span"3Keith Thompson
24 Mar 24 i     +- Re: "span"1Ben Bacarisse
25 Mar 24 i     `- Re: "span"1Lawrence D'Oliveiro
23 Mar 24 +* Re: "span"2Ben Bacarisse
23 Mar 24 i`- Re: "span"1Kaz Kylheku
23 Mar 24 +- Re: "span"1fir
23 Mar 24 `- Re: "span"1Blue-Maned_Hawk

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal