Sujet : Re: So You Think You Can Const?
De : antispam (at) *nospam* fricas.org (Waldek Hebisch)
Groupes : comp.lang.cDate : 12. Jan 2025, 23:29:36
Autres entêtes
Organisation : To protect and to server
Message-ID : <vm1foe$2s6l0$1@paganini.bofh.team>
References : 1 2 3 4 5 6 7 8 9
User-Agent : tin/2.6.2-20221225 ("Pittyvaich") (Linux/6.1.0-9-amd64 (x86_64))
Ben Bacarisse <
ben@bsb.me.uk> wrote:
Julio Di Egidio <julio@diegidio.name> writes:
On 09/01/2025 02:09, Ben Bacarisse wrote:
Julio Di Egidio <julio@diegidio.name> writes:
static AvlTree_t const *AvlTree_node(
void const *pk, AvlTree_t const *pL, AvlTree_t const *pR
) {
AvlTree_t *pT;
>
pT = malloc(sizeof(AvlTree_t));
>
if (!pT) {
return NULL;
}
>
pT->pk = pk;
pT->pL = pL;
pT->pR = pR;
>
return pT;
}
Just on a side issue, I prefer to make tests like this positive so I'd
write:
static AvlTree_t const *AvlTree_node(
void const *pk, AvlTree_t const *pL, AvlTree_t const *pR
) {
AvlTree_t *pT = malloc(*pT);
if (pT) {
pT->pk = pk;
pT->pL = pL;
pT->pR = pR;
}
return pT;
}
I'm not going to "make a case" for this (though I will if you want!) --
I just think it helps to see lots of different styles.
>
That is *more* error prone,
I would be happy for you to expand on why you say that.
Julio did not want to give his reasons, but I have reasons to
prefer "negative" version too. Namely, significant trouble
with malloc is ensuring correct handling of failing case.
Since this code is not excercised by normal execution, this
should be done by robust coding pattern. In particular,
it is easier to check correctness when handling code is
immediately after 'malloc' and the test. So
AvlTree_t *pT = malloc(*pT);
if (!pT) {
return pT;
}
...
makes quite visible that handling is there and it is rather
minimal (in particular caller have to cope with null pointer
return). That is easily lost in "posive" version, where
error handling may be far away from the allocation and test.
Basically, this is similar idea to "defer" discussed in
another thread, just in this case requires no language
extention and simply adopting appropriate coding style
gives the effect.
-- Waldek Hebisch