I have some code that I am porting from an SGI system using the MIPS compiler. It has functions that are declared to have double return type. If the function can't find the right double, those functions return "NULL"开发者_StackOverflow中文版
The intel C compiler does not like this, but I was trying to see if there is a compiler option to enable this "feature" so that I can compile without changing code. I checked the man page, and can't seem to find it.
Thanks
Example of the code that currently exists, and works fine with MIPS
double some_function(int param){
double test = 26.25;
if(param == 10){
return test;
}
return (NULL);
}
the intel compiler complains: error: return value type does not match the function type
There might be a "NaN" (not a number) capability, via compiler options. But that still won't be a null.
Based on your comment:
I just checked, and the calling functions just use it as if it is a valid double (in an if statement)
I would just modify the function to return 0;
instead of return NULL;
It's not a compiler option, but you could #define NULL 0
to (in theory) get the desired effect.
Are you sure they don't return pointer-to-double? A NULL double is meaningless, since zero is a valid value for double.
NULL
doesn't necessarily have a special meaning when it is returned from a function. If you want to indicate that a function did not complete successfully, the common technique is to return some value that would never be returned under normal circumstances. Usually, this means returning an invalid value. When a function returns a pointer, it often uses NULL
as a return value signaling an error since a NULL
pointer is rarely a value that the user would expect the function to return.
The constant NULL
only has meaning in the context of pointers, and since you are returning a scalar value the compiler is griping at you about using NULL
. Instead of returning NULL
, find some value that could never be a valid return value and use it as your error indicator. To make it more clear what you are doing, alias that value with a constant using #define AN_ERROR_OCCURED <<someval>>
to avoid using "magic numbers".
Another common way to do it is to use the errno
global (see errno.h). If your function encounters an error, set errno
to some non-zero value before returning. The code calling your function will then can check for and handle errors using something like if (errno) {...}
.
Yet another method is to have the function return zero if successful and a non-zero error code otherwise. If the user needs to get data back from the function, an extra "return buffer" pointer would have to be passed to the function.
I think I will just use #ifdef INTEL for a compiler flag, and define the return as zero for that compile time option. Kind of a pain, but seems to be the best way.
精彩评论