2

Suppose I have a function that returns an instance of a struct with the following declaration:

struct data API(void);

Suppose also that there is a chance for the function to fail with an error during the execution. What is the best way to indicate that an error occurred?

A solution that comes to mind is to create a structure that nests the actual data structure along with an exit status, like so:

struct result {
    signed int exit;
    struct data;
}

and change the function declaration to the following:

struct result API(void);

Is there a better way to do this? I am well aware of the de-facto standard of writing to a structure pointed to by an argument, e.g. int API(struct data *location).

6

We can discuss for ages what would be the best way, but the truth is that anything works as long as you are consistent with it.

Your solution has a major drawback: you need one additional structure for each structure you have. It might work well in a small application, but it doesn't scale very well.

An option would be to enforce (by coding standards) to include in each structure a member valid or error, which indicates if the object is in a valid state or if any error occurred during the last processing of the object. The good news is that you might be able to write some syntax analyzers that make sure this rule is followed by all your structures.

7

I'm aware of three ways of signaling error from a C function:

  1. Every function returns an error code. If a function needs to return data (for example, a result of an I/O operation), it writes the data to a pointer, which is provided by a parameter.
    [This is the de-facto standard, which the O.P. had mentioned.]

  2. Function writes their errors to a global error variable. The error variable is well known (a priori known) to the calling code. The function returns data (or void). The calling code checks the global variable.

  3. The function returns a struct, which contains both error information and data.

All of these schemes put the burden of checking for error on the immediate calling code. The C language doesn't treat error codes like C++ treats exceptions..

1

Several choices: a. Your function returns a Boolean for success or an error code, and returns the structure through a pointer parameter. b. Your function returns a structure, and returns a Boolean or an error code through a pointer parameter. c. You return a structure which can be checked for validity.

Personally I prefer a. in C. In other languages you have exceptions or optionals. Swift 5.0 has a type “Result” in its standard library for this exact purpose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.