Re: "not-const" qualifier for C

Liste des GroupesRevenir à l c 
Sujet : Re: "not-const" qualifier for C
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.c
Date : 25. Apr 2024, 01:13:07
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20240424133951.155@kylheku.com>
References : 1
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2024-04-24, Thiago Adams <thiago.adams@gmail.com> wrote:
Motivation sample:
>
struct X {
      const char* const type;
};
>
struct X * make_x(){
   struct X * p = malloc(sizeof *p);
   if (p)
   {
>
       p->type = strdup("X");  // *** error, type is const ***
>
       if (p->type == NULL)
       {
          free(p);
          p = NULL;
       }
   }
   return p; //ok
}

Different idea: allow all conversions without a cast which only
add qualifiers anywhere in the type:

  struct X {
    const char* const type;
  };

  struct mutable_X {
    char* type;
  };

 struct X * make_x()
 {
    struct mutable_X * p = malloc(sizeof *p);
    if (p)
    {
 
        p->type = strdup("X");
 
        if (p->type == NULL)
        {
           free(p);
           p = NULL;
        }
    }
    return p; // ok: X differs from mutable_X only in having more qualifiers
 }

Regarding freeing, we fix that with a different freeing interface:

  extern void cvfree(const volatile void *p);

  void x_destroy(struct X * p)
  {
    cvfree(p->type); //no warning: conversion only adds qualifiers
  }

Freeing is not mutation; it makes sense to free via a qualified
pointer. Const objects can die, e.g:

  {
     const int x = 42;
  }

The free function taking a void * is a misfeature in the C library.

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

Date Sujet#  Auteur
24 Apr 24 * "not-const" qualifier for C6Thiago Adams
25 Apr 24 +* Re: "not-const" qualifier for C3Kaz Kylheku
25 Apr 24 i`* Re: "not-const" qualifier for C2Thiago Adams
25 Apr 24 i `- Re: "not-const" qualifier for C1Kaz Kylheku
25 Apr 24 +- Re: "not-const" qualifier for C1Blue-Maned_Hawk
23 May 24 `- Re: "not-const" qualifier for C1Lawrence D'Oliveiro

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal