Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Throw error on parameter check or let it hit the fan?

I have a simple design(?) question.

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;
}

I have a couple of questions on this, with no intention of re opening some holy war.

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;
        }
       ...
}

update

This is kind of a toy program, just trying to practice some stuff. The question excedes that fact. Maybe I should rephrase to "how to handle errors without (OOP) exceptions".

Also considering testing n before doing the call, but don't like it as much.

Any thoughts? Thanks in advance.

like image 841
Tom Avatar asked Sep 07 '10 04:09

Tom


3 Answers

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!

like image 181
bdhar Avatar answered Sep 28 '22 06:09

bdhar


If -1 would not be returned by the function anyway, by all means return -1. But if passing n=0 won't break the function, then it isn't really needed. I assume that n is the size of the array m.

Handling errors is a matter of preference. OpenGL handles errors by returning an error code (-1 or otherwise) when a function fails. The error code is returned througha call to GetLastError() (or something like that). This seems like an ideal error handling solution.

like image 29
Alexander Rafferty Avatar answered Sep 28 '22 06:09

Alexander Rafferty


There are special floating point values you can use if you want - for example, if your floating-point implementation supports quiet NaNs (Not-a-Number) then you can use the NAN macro from math.h:

#include <math.h>
float foo(float *m,size_t n)
{
     if (n == 0) return NAN;

     ...
}
like image 25
caf Avatar answered Sep 28 '22 07:09

caf