bug-gnulib
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Type-safe typecasts


From: Marc Nieper-Wißkirchen
Subject: Re: Type-safe typecasts
Date: Tue, 6 Apr 2021 21:34:17 +0200

CCing Bruno because of his involvement with the Gnulib list modules.

Disallowing NULL list elements could break existing code that actually uses them but returning elements with type void * instead of const void * would be much less incompatible. Code can trivially be ported to such an updated interface (for example, in my snippet above, I would have to replace 'const void *e' with 'void *e', All in all, it would make working with the code a lot easier.

For lists where there are no non-null list elements, one could add

void *gl_list_iterator_next_element_or_null (gl_list_iterator_t iter, gl_list_node_t *node_ptr)
{
  void *e;
  return gl_list_iterator_next (iter, &e, node_ptr) ? e : NULL;
}

to the global API (modulo a better name for the procedure).


Am Di., 6. Apr. 2021 um 21:20 Uhr schrieb Paul Eggert <eggert@cs.ucla.edu>:
On 4/6/21 12:13 PM, Marc Nieper-Wißkirchen wrote:
> gl_list_iterator_next has to return two things: An element (represented by
> a const void *) and a boolean value. As elements may be NULL

Ah, OK, then that's the problem. The API shouldn't allow null elements.
They're not that useful anyway. If they really are needed for some
lists, I suppose one could have a more-complicated API to return them
(by setting a bool elsewhere); but usually they aren't.

> So to make my original code portable C, I would have to code
>
> ...
> const void *e;
> while (gl_list_iterator_next (&i, &e, NULL))
>   {
>     struct foo *foo = (void *) e;
>     ++foo->bar;
>   }
> ...
>
> The const typecast is, unfortunately, still needed to silence compiler
> warnings

Yes, that would be portable. But that cast indicates another problem
with the API. It should return void *, not void const * (think of strchr
as the model here). The API should discourage type-casts, since they're
more dangerous than the alternatives.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]