I'm writing a simple program that has a couple of functions that look like these:
float foo (float* m,size_t n){
float result;
//do some calculations, for example a sum
return result / n;
}
Should I add a sanity check on the n
? If so, how should I let the caller know?
Returning -1
looks weird on floats;
float foo(float *m,size_t n){
if (n == 0) return -1f
...
}
My other option is an out parameter
float foo(float *m,size_t n, int *error){
if (n==0){
*error = 1;
return 0f;
}
...
}
This is kind of a toy program, just trying to practice some stuff. The question exceeds that fact. Maybe I should rephrase to "how to handle errors without (OOP) exceptions".
I'm also considering testing n
before doing the call, but don't like it as much.
Any thoughts?
I guess your out parameter
option is a good one. But I guess it would be better the other way. Use the out parameter to get the result and the return value to denote the status of the call. Like this
int foo(float *m, size_t n, float* result)
{
if(someFailureCondition)
return ERROR; // ERROR being an error integer
// else
// do some calculation
// set your result
return NO_ERROR; // NO_ERROR being an integer
}
Edit: The return value can be more verbose to denote the current state of the out parameter. See Jamesdlin's comment!