Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return code values in an embedded system written in C

Tags:

c

coding-style

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

like image 453
Renjith G Avatar asked Sep 20 '11 10:09

Renjith G


People also ask

How do you return a value in C?

If a return value isn't required, declare the function to have void return type. If a return type isn't specified, the C compiler assumes a default return type of int . Many programmers use parentheses to enclose the expression argument of the return statement. However, C doesn't require the parentheses.

Why do we write return 1 in C?

return 1 in the main function means that the program does not execute successfully and there is some error. return 0 means that the user-defined function is returning false. return 1 means that the user-defined function is returning true.

How is C used in embedded systems?

C provides optimized machine instructions for the given input, which increases the performance of the embedded system. Most of the high-level languages rely on libraries, hence they require more memory which is a major challenge in embedded systems.


2 Answers

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>).

like image 155
Fred Foo Avatar answered Sep 30 '22 21:09

Fred Foo


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?

like image 27
wormsparty Avatar answered Sep 30 '22 19:09

wormsparty