4 ms·
If I'm not mistaken, the first example is equivalent to the following purely structured code: void * const p = malloc(25); if (p != NULL) { void * con
by augustk 6y ago
If I'm not mistaken, the first example is equivalent to the following purely structured code:
void * const p = malloc(25);
if (p != NULL) {
void * const q = malloc(25);
if (q != NULL) {
if (mtx_lock(&mut) != thrd_error) {
mtx_unlock(&mut);
}
free(q);
}
free(p);
}
At least to me, this flow is much easier to understand.
- avianes 6y agoTo me, your example is not really easier to understand than the defer version. The complete flow is immediately apparent in your example, but the "effective" flow (the two malloc and the mutex) is harder to identify. And now imagine the same thing with 10 or more nested conditions. With defer or goto, it allows you to mentally split the logic in two parts: on one hand the "effective" algorithm; and on the other hand the resource release.
- jiripospisil 6y agoI think the difference would be more pronounced if there was actually any code that works with the allocated resources. Imagine you wanted to early return because of some other condition. With your code, you cannot just `return` a value, you need to handle the deallocations, and you would be back to GOTOs in no time. Maybe a personal preference but I also like to keep my code flat. You are already 3 indentation levels deep without any logic in it.