Alex Rivera | Logout

What is the best way to return an error from a function when I'm already returning a value?

Asked 2008-11-15T00:04:12.200
42

I wrote a function in C that converts a string to an integer and returns the integer. When I call the function I also want it to let me know if the string is not a valid number. In the past I returned -1 when this error occurred, because I didn't need to convert strings to negative numbers. But now I want it to convert strings to negative numbers, so what is the best way to report the error?

In case I wasn't clear about this: I don't want this function to report the error to the user, I want it to report the error to the code that called the function. ("Report" might be the wrong word to use...)

Here's the code:

s32 intval(const char *string) {
    bool negative = false;
    u32 current_char = 0;

    if (string[0] == '-') {
        negative = true;
        current_char = 1;
    }

    s32 num = 0;
    while (string[current_char]) {
        if (string[current_char] < '0' || string[current_char] > '9') {
            // Return an error here.. but how?
        }

        num *= 10;
        num += string[current_char] - '0';
        current_char++;
    }

    if (negative) {
        num = -num;
    }

    return num;
}
Edit
Report

1 Answer

8

The os-style global errno variable is also popular. Use errno.h.

If errno is non-zero, something went wrong.

Here's a man page reference for errno.

answered 2008-11-15T00:08:59.337

Your Answer