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

前端 未结 8 1916
盖世英雄少女心
盖世英雄少女心 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:56

    In general I prefer the way Jon Skeet proposed, ie. returning a bool (int or uint) about success and storing the result in a passed address. But your function is very similar to strtol, so I think it is a good idea to use the same (or similar) API for your function. If you give it a similar name like my_strtos32, this makes it easy to understand what the function does without any reading of the documentation.

    EDIT: Since your function is explicitly 10-based, my_strtos32_base10 is a better name. As long as your function is not a bottle-neck you can then, skip your implementation. And simply wrap around strtol:

    
    s32
    my_strtos32_base10(const char *nptr, char **endptr)
    {
        long ret;
        ret = strtol(nptr, endptr, 10);
        return ret;
    }
    

    If you later realize it as an bottleneck you can still optimize it for your needs.

提交回复
热议问题