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

前端 未结 8 1914
盖世英雄少女心
盖世英雄少女心 2020-12-13 13: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 num

8条回答
  •  悲&欢浪女
    2020-12-13 13:58

    a common way is to pass a pointer to a success flag like this:

    int my_function(int *ok) {
        /* whatever */
        if(ok) {
            *ok = success;
        }
        return ret_val;
    }
    

    call it like this:

    int ok;
    int ret = my_function(&ok);
    if(ok) {
        /* use ret safely here */
    }
    

    EDIT: example implementation here:

    s32 intval(const char *string, int *ok) {
        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?
                    if(ok) { *ok = 0; }
            }
    
            num *= 10;
            num += string[current_char] - '0';
            current_char++;
        }
    
        if (negative) {
            num = -num;
        }
        if(ok) { *ok = 1; }
        return num;
    }
    
    int ok;
    s32 val = intval("123a", &ok);
    if(ok) {
        printf("conversion successful\n");
    }
    

提交回复
热议问题