What should I return for errors in my functions in C?

I am currently returning -1 in my custom C functions if something is wrong, and 0 for success. For example, to work with a linked list and some function, you need a non-empty list for proper operation. If the list passed as an argument is empty, I return -1 (error) and 0 if it is not empty and the function works without problems.

Should I maybe return 1 instead of -1?

Is this the standard way to do things in C, or do you recommend a different approach?

+4
source share
4 answers

Returns a nonzero value to indicate a failure. Thus, you can write function calls as follows:

if(func_call()) { doErrorHandling(); } 

This convention will allow you to use any value !0 to indicate a specific error, and this will allow you to use one variable in the same way. Thus, the if body, shown in the above example, can then have a switch statement to handle specific errors.

You can do it differently - but if you decide to do it, stick to the convention - the win32 API (and the other API I used) unfortunately mix and match the conventions.

+8
source

Sounds wonderful. -1 is used in the I / O function because a positive return value usually means success and the number of bytes processed. If you have several ways when a function may go wrong, then you can either return different integers or set a global error variable (errno is used by the standard library) to contain the error code.

In terms of style, I prefer not to return status codes, since my functions cannot (purely) return anything else. Instead, I have to check the input before calling the function. But this is subjective and contextual.

+2
source

I suggest you find a way to format a fully informative line read by a person at the point of error where all the information is still available, and develop a way to overcome it the rest of the program, through the user, his mobile phone, to your development team for analysis.

It seems to me that this is an important function of any design if you want to produce better software faster. Killing error information is a major crime, and C is no excuse.

-1
source

There are many schemes - but no matter what you do, do it sequentially!

If you don't have many bad conditions, just use 0 for the error. This is because error tests are written in a simple way:

 if (!list_insert(...)) { handle_error; } 

Otherwise, answers below zero are useful for use with normal answers> = 0. You can use this for functions such as list length, which under normal conditions will not be negative. Or, if you need a lot of error codes (-1 - nonexentting, -2 - not found, -3 ..., ...)

-5
source

Source: https://habr.com/ru/post/1300547/


All Articles