开发者

What to return in C when need to throw an exception in other language such as C++?

I implemented a htoi(hex integer to octal integer) function in C. The function signature is as following:

int htoi(char* s);

The basic logic is fairly simple and my main concern is how to deal with the extreme test data such as invalid hex number such as oxazzz, ox???DFSLA. Obviously, some magic number would not work, since the result could be any integers.

One solution I would like to take is change the function sig开发者_JAVA百科nature such as:

int htoi(char* s, bool* error);

And set error as true when s is not a valid hex number.But it seems that it is not a nice solution. Therefore, what should be the best practice to handle this situation since no exception throw mechanism available in C?


Take a look at how strtol(3) does it. Not saying it's ideal, just an example.


I would suggest to pass output variable in the function signature and return values as SUCESS/FAILURE

error_type function_name ( input_variable, *input_output_variable);


int htoi(char* s, int* result);

return 0 (or -1, or whatever you want) on failure.

Another option is:

int* htoi(char* s, int* result);

You return the pointer to result (the same pointer you passed in) if successful, NULL on failure.

I tend to like the latter style; if (htoi(myString, &myInt) == NULL) { /* bad thing */ }


I would say you should document the fact that calling the function with an invalid string results in undefined behaviour. You can then return whatever number you like. I would also implement an IsHexNumber function that tests for a valid number. You thus give the users of your function a means by which they can write code that never passes a bad string, and you offload the error handling to a higher part of the code, which is where it belongs.


The idea of using an extra argument is quite common. Use a pointer for the error argument, though. An even better idea is to return success/failure and store the actual result through a pointer.

Also, some C standard library functions (the strtol family) handle this by specifying that a function sets errno on error. This is another possibility, although it leads to the somewhat cumbersome idiom

errno = 0;  // errno may have been set previously
x = strtol(str, NULL, 10);
if (errno)
    // handle error


Returning an error code seems to be the de facto standard, but in my opinion it's quite tedious and error prone.

Instead, you could use some exception handling system in C to actually throw an exception.

For example, I'm developing exceptions4c, and there are many other alternative libraries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜