"not-const" qualifier for C

Liste des GroupesRevenir à l c 
Sujet : "not-const" qualifier for C
De : thiago.adams (at) *nospam* gmail.com (Thiago Adams)
Groupes : comp.lang.c
Date : 24. Apr 2024, 21:24:52
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v0bma4$2g9n9$1@dont-email.me>
User-Agent : Mozilla Thunderbird
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
}
void print(struct X * p){
   prinf("%s", p->type);
}
void x_destroy(struct X * p)
{
    free(p->type); // *** warning const to non-const ***
}
Now consider we have the keyword "mutable" that removes const from struct members.
struct X {
      const char* const type;
};
struct X * make_x(){
   mutable struct X * p = malloc(sizeof *p);
   if (p)
   {
       p->type = strdup("X");  //OK
       if (p->type == NULL)
       {
          free(p);
          p = NULL;
       }
   }
   return p; //ok
}
void print(struct X * p){
   prinf("%s", p->type);
}
void x_destroy(mutable struct X * p)
{
    free(p->type); //no warning
}

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