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

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

    Well, the way that .NET handles this in Int32.TryParse is to return the success/failure, and pass the parsed value back with a pass-by-reference parameter. The same could be applied in C:

    int intval(const char *string, s32 *parsed)
    {
        *parsed = 0; // So that if we return an error, the value is well-defined
    
        // Normal code, returning error codes if necessary
        // ...
    
        *parsed = num;
        return SUCCESS; // Or whatever
    }
    

提交回复
热议问题