Error handling in C is sometimes done by using goto and labels. One of examples in the Linux kernel:
static struct avc_node *avc_alloc_node(void) { struct avc_node *node; node = kmem_cache_zalloc(avc_node_cachep, GFP_ATOMIC); if (!node) goto out; INIT_RCU_HEAD(&node->rhead); INIT_HLIST_NODE(&node->list); avc_cache_stats_incr(allocations); if (atomic_inc_return(&avc_cache.active_nodes) > avc_cache_threshold) avc_reclaim_node(); out: return node; }
There's a trick with the usage of do/while construction that allows to write the same without using goto label. The idea is presented on below:
// with goto label if (!bar()) { goto error; } someValue = baz(); error:
// with do/while construction do { if (!bar()) { break; } someValue = baz(); } while (0);
That's really obscure! Good for a blog or for a cafe (or beer) talk, but I hate people who make this in a real code. People should understand that just because something is possible, it doesn't mean that it should be done.
ReplyDeleteI agree with you!
Delete