3 ms·
In C you can return a struct, however a better approach is to use a context object which also contains error information, like: ctx_t* ctx = ctx_new();
by Crinus 7y ago
In C you can return a struct, however a better approach is to use a context object which also contains error information, like:
ctx_t* ctx = ctx_new();
if (!ctx) ... fail ...
if (!ctx_parse(ctx, code)) {
show_error_message(ctx_erline(ctx), ctx_ercol(ctx));
... more fail ...
ctx_free(ctx); /* often done in a goto'd section to avoid missing frees*/
}
This also allows you to extend the APIs functionality, error information, etc in the future while remaining backwards compatible.
- alyandon 7y agoThat is very similar to the way I handled errors back in my C days.
- bjourne 7y agoYep, you're absolutely right. But don't tell me that is simple! :)
- machinecoffee 7y agoWhich is great, except that ctx_new() requires a malloc, which then can fail, and now you can't even explain why the thing failed, as you have no context info. You also have to worry about all of the ctx objects you've created along the way, to free them up as you recover from the low memory error.