Would this be a valid use of NULL in C or are there other ways to solve this problem that are preferred?
// Send data
// cb_push returns NULL if it is successful
char uart_send(char c) {
void* ret = cb_push(w_buffer, &c);
if (ret != NULL) return c;
SETBIT(UCSR0B, UDRIE0);
return NULL;
}
In Java I would do like this, sort of, but in C I don’t know what is good practice.
It’s not really defined and there are different approaches depending on the library and/or function you’re using. In general, there’s no way to differentiate between
0andNULL(in fact,NULLis usually just a preprocessor macro expanding to0).In general, the following possibilities are used, sometimes even matched within one library depending on the usage:
0usually indicates some kind of error.mainentry points) usually return0in case there hasn’t been any error.0if something hasn’t been successfull (i.e. they return a boolean value).std::string::find()will return-1if the sub string couldn’t be found. This is however wrapped/hidden behind a constant named value (std::string::npos) to avoid throwing around “magic values”.Is there a perfect way? I don’t think so, but it really depends on the specific use case. If you return a pointer, returning 0 in case of a mistake is just perfect. If you’re returning status codes, I’d go with either macros (similar to windows API) or enums. Don’t even worry about any specific values – only use the names.