Concept

How can a quadratic roots function return error codes?

ComputerScienceOne / Error Handling By Design

"As an example, let’s revisit the quadratic roots example in Section 18.3.2. By returning the two output values via pass by reference variables, we freed up the return value. We can now modify our function to return an integer indicating an error code instead. Previously we had identified several different types of errors: division by zero (if a = 0), complex roots (if b 2 − 4 ac < 0) and a NULL pointer error if the variables passed by reference were NULL. We can now modify our function to check for these errors and return an appropriate error code. We return zero in the event that no error was encountered.\n\nint quadraticRoots(double a, double b, double c,\n\ndouble *root1, double *root2) {\n\nif(a == 0) {\n\nreturn 1;\n\n} else if( b*b - 4*a*c < 0 ) {\n\nreturn 2;\n\n} else if(root1 == NULL || root2 == NULL) {\n\nreturn 3;\n\n}\n\ndouble discriminant = sqrt(b*b - 4*a*c);\n\n*root1 = (-b + discriminant) / (2*a);\n\n*root2 = (-b - discriminant) / (2*a);\n\nreturn 0;\n\n}\n\nNow when a function invokes our quadraticRoots() it can check to see what kind of"

Related Ideas