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
- How can the return value communicate errors when roots are passed by reference?ComputerScienceOne · Quadratic Roots
- How can enumerated types be used for error codes in C?ComputerScienceOne · Using Enumerated Types for Error Codes
- Why are enumerated types better than arbitrary integer error codes?ComputerScienceOne · Enumerated Types
- How can conditionals handle invalid inputs and special cases in a quadratic roots program?ComputerScienceOne · Quadratic Roots Revisited
- How can pass-by-reference parameters return both roots of a quadratic equation?ComputerScienceOne · Quadratic Roots
- How does the Java quadratic roots program check errors and calculate its roots?ComputerScienceOne · Quadratic Roots Revisited
- Why must software handle errors in addition to avoiding bugs?ComputerScienceOne · Error Handling
- What kinds of user input can cause problems in a quadratic-roots program?ComputerScienceOne · Computing Quadratic Roots