C: Throw an error while checking the parameters or let it get into the fan?

I have a simple question (?).

I am writing a simple program that has several functions that look like this.

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 about this, with no intention of renewing some kind of holy war.

Should I add a health check on n? If so, how can I tell the caller?

The return -1looks weird over the floats;

float foo(float *m,size_t n){
     if (n == 0) return -1f

     ...
  }

Another option is the out parameter

float foo(float *m,size_t n, int *error){

        if (n==0){
           *error = 1;
            return 0f;
        }
       ...
}

Update

This is a kind of toy program, just trying to practice something. This question stems from this fact. Perhaps I should rephrase "how to handle errors without exceptions (OOP)."

n , .

? .

+5
4

, out parameter . , -. out, , .

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: out. . Jamesdlin!

+6

-1 , -1. n = 0 , . , n - m.

- . OpenGL , (-1 ) . GetLastError() ( - ). .

+2

, , - , NaNs (Not-a-Number), NAN math.h:

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

     ...
}
+1

, , .

? 0 n, , assert, , . , , .

, , , , assert, , :

if (n == 0)
{
    assert(0);
    return NAN; /* Or return some error code */
}
+1

All Articles