开发者

Return code values in an embedded system written in C

Most of the places I 开发者_运维问答have seen the return code values are done like this,

for success status return , #define SUCCESS 0 and other no zero numbers for all other error cases.

My question is , why we selecetd zero for SUCCESS case? Is there any specific programming best practice concerns for that?

/R


It's an old C habit to return 0 for success and some other code for errors, so you can say:

int error = do_stuff();
if (error) {
    handle_error(error);
}

However, predicates usually work the other way around, returning 1 for "success" (or true from <stdbool.h>).


You have to differenciate between different errors, there can be MaxInt - 1 different ones.

If 0 was an error and 1 was success, how could you tell the difference between all errors?


Zero often means success because zero is the only integer value that evaluates to false. All other integer values evaluate to true and they are meant for various error codes.

It might seem a bit weird and logically inverted, but because success is just success and errors can be different, the above convention is chosen often.

In fact, this is the most rational convention if the return value of a function is used not only as a success/failure indicator, but as an error code too. If the error code is stored, say in an additional output parameter, then returning 1 for success and 0 for failure makes more sense.

Imagine what the condition would be in the case of 0 being success:

if (errcode = func()) {
  /* error handling */
}

versus the more cumbersome:

if ((errcode = func()) != 1) {
  /* error handling */
}


This is an operating system convention.

http://en.wikipedia.org/wiki/Exit_status

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜