3 ms·
I'm personally fond of filling an error buffer, but a bit more explicitly than just an int. typedef struct APIError { int code; char *descr
by lyinsteve 12y ago
I'm personally fond of filling an error buffer, but a bit more explicitly than just an int.
typedef struct APIError {
int code;
char *description;
};
/**
* Returns NULL and fills the error parameter if creation was unsuccessful.
*/
Something APICreateSomething(bool param1, int param2, APIError *error);
So common execution would be:
APIError error;
Something something = APICreateSomething(true, 3, &error);
if (error) {
// handle error...
}
And if the user passed in NULL for the error parameter, then that's their problem, and they won't get error information.
- TillE 12y agoIf that char* is just a pointer into a static array which maps error codes to strings, I'd generally prefer to use a separate API to do that. If it's a freshly allocated string that needs to be freed by the caller, well, that's one of many reasons I never enjoy my time with C.