C - What is the proper format to allow a function to show an error was encountered?

Posted by BrainSteel on Stack Overflow See other posts from Stack Overflow or by BrainSteel
Published on 2013-06-30T22:11:14Z Indexed on 2013/06/30 22:21 UTC
Read the original article Hit count: 204

Filed under:
|
|

I have a question about what a function should do if the arguments to said function don't line up quite right, through no fault of the function call. Since that sentence doesn't make much sense, I'll offer my current issue. To keep it simple, here is the most relevant and basic function I have.

float getYValueAt(float x, PHYS_Line line, unsigned short* error)

    *error = 0;    

    if(x < line.start.x || x > line.end.x){
        *error = 1;
        return -1;
    }

    if(line.slope.value != 0){
        //line's equation: y - line.start.y = line.slope.value(x - line.start.x)
        return line.slope.value * (x - line.start.x) + line.start.y;
    }

    else if(line.slope.denom == 0){
        if(line.start.x == x)
            return line.start.y;
        else{
            *error = 1;
            return -1;
        }
    }

    else if(line.slope.num == 0){
        return line.start.y;
    }
}

The function attempts to find the point on a line, given a certain x value. However, under some circumstances, this may not be possible. For example, on the line x = 3, if 5 is passed as a value, we would have a problem. Another problem arises if the chosen x value is not within the interval the line is on. For this, I included the error pointer. Given this format, a function call could work as follows:

void foo(PHYS_Line some_line){
    unsigned short error = 0;
    float y = getYValueAt(5, some_line, &error);
    if(error)
        fooey();
    else
        do_something_with_y(y);
}

My question pertains to the error. Note that the value returned is allowed to be negative. Returning -1 does not ensure that an error has occurred. I know that it is sometimes preferred to use the following method to track an error:

float* getYValueAt(float x, PHYS_Line line);

and then return NULL if an error occurs, but I believe this requires dynamic memory allocation, which seems even less sightly than the solution I was using. So, what is standard practice for an error occurring?

© Stack Overflow or respective owner

Related posts about c

    Related posts about function