Sujet : Re: Code guidelines
De : thiago.adams (at) *nospam* gmail.com (Thiago Adams)
Groupes : comp.lang.cDate : 03. Sep 2024, 17:37:02
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vb7dve$3d5mv$2@dont-email.me>
References : 1 2 3 4 5 6
User-Agent : Mozilla Thunderbird
On 03/09/2024 13:23, Thiago Adams wrote:
...
I will give a sample
In my code I have
if (obj->member1 &&
obj->member1->member2 &&
obj->member1->member2->member3)
{
}
The contract is
* obj->member1 CAN be null
* obj->member1->member2 CANNOT be null
* obj->member1->member2->member3 CAN be null
So I can write just
if (obj->member1 &&
obj->member1->member2->member3)
{
}
but...maybe, is better to be a little redundant here?
I think I prefer to leave "obj->member1->member2 && " even if I know
it should not be null.
if (obj->member1 &&
obj->member1->member2 &&
obj->member1->member2->member3)
{
}
I also have a interesting sample with linked list
struct item {
char* title;
struct item* next; //can be null
};
struct list {
struct item* head; //can be null
struct item* tail; //can be null
};
void list_push_back(struct list* list, struct item* p_item)
{
if (list->head == NULL) {
list->head = p_item;
//tail also should be null
}
else {
//When the head is null tail is also null
//if head is not null then tail is not null
//So tail is not null here.. assert works as assume
assert(list->tail != nullptr);
//next can be null or not null..however for the tail node
//next IS/MUST BE null
assert(list->tail->next == nullptr);
list->tail->next = p_item;
}
list->tail = p_item;
}
assert in this case works as "assume" and "check".
For instance,
We assume "assert(list->tail != nullptr);" because we access it directly here
list->tail->next = p_item;
We also assume "assert(list->tail->next == nullptr)" otherwise we could have a memory leak overriding next.