Deliberately returning an invalid value or type

As a suggested exercise by Stephen Kochan, “Programming in C” (3rd ed.) I want to add some function to a function strToIntthat turns a string into an integer. The function has a return value type int, which is fine if a valid literal with a passed string (for example, "123" or "13"). But if the string contains any non-numeric values ​​(for example, "12x3", "foo"), the error message should be printed and the function completed. Since the type of return int, you need to return an integer, but in this case this can be misleading. So my question is: what should be returned in such a case so that the return value / type explicitly refers to the fact,that an invalid string literal was passed and cannot be confused with a valid return value?

int strToInt(const char string[])
{
    int i = 0, intValue, result = 0;

    // check whether string passed is a valid literal
    while (string[i] != '\0')
    {
        if (string[i] < '0' || string[i] > '9')
        {
            printf("ValueError: Invalid literal\n");
            return;                            // what should be returned here?
        }
        ++i;
    }

    for (i = 0; string[i] >= '0' && string[i] <= '9'; ++i)
    {
        intValue = string[i] - '0';
        result = result * 10 + intValue;
    }

    return result;
}
+4
3

// ?

, . . , , . :

#include <stdbool.h>

bool strToInt(const char string[], int* outInt) {

    // check whether string passed is a valid literal
    while (string[i] != '\0')
    {
        if (string[i] < '0' || string[i] > '9')
        {
            printf("ValueError: Invalid literal\n");
            return false;
        }
    }

    int result = 0;
    for (int i = 0; string[i] >= '0' && string[i] <= '9'; ++i)
    {
        intValue = string[i] - '0';
        result = result * 10 + intValue;
    }

    if (outInt) // Or you may move the check earlier and return false too
      *outInt = result;

    return true;
}

, , bool. , , . , .

+3

, " " .

. , C , getc, , int, char. , -1 .

, strtod, 0, double ( , ). - , ( ) errno,

Errno, -, unix . , , . , - , errno, , .

+2

, strto* - ( ), , . - , .

, 12x3 12, ​​ . , , .

In case strtol( [long int strtol(const char *nptr, char **endptr, int base);]) from the page, manwe can see that when endptrset to the end of the line, this means that the entire line I resolved successfully. In the case of a partial conversion, that endptrwill not point to the middle of the line. The same method that simulates a function strto*, we see that it sets the errnocorresponding number to indicate various problems ( ERANGEetc.) - at the same time, you can configure it to provide the user with an accurate error report.

0
source

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


All Articles