Concept
How can enumerated types be used for error codes in C?
ComputerScienceOne / Using Enumerated Types for Error Codes
"19.4. Using Enumerated Types for Error Codes\n\nLet’s apply enumerated types to our quadraticRoots() function example from before. First, we define our enumerated type which includes all types of errors including a NO_ERROR type. Note that we start with NO_ERROR as its value will be zero following our convention.\n\ntypedef enum {\n\nNO_ERROR,\n\nDIV_BY_ZERO_ERROR,\n\nCOMPLEX_ROOT_ERROR,\n\nNULL_POINTER_ERROR\n\n} ErrorCode;\n\nNow in the quadraticRoots() function, we can return the appropriate error code as an enumerated type value.\n\nErrorCode quadraticRoots(double a, double b, double c,\n\ndouble *root1, double *root2) {\n\nif(a == 0) {\n\nreturn DIV_BY_ZERO_ERROR;\n\n} else if( b*b - 4*a*c < 0 ) {\n\nreturn COMPLEX_ROOT_ERROR;\n\n} else if(root1 == NULL || root2 == NULL) {\n\nreturn NULL_POINTER_ERROR;\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 NO_ERROR;\n\n}"
Related Ideas
- Why are enumerated types better than arbitrary integer error codes?ComputerScienceOne · Enumerated Types
- How can a quadratic roots function return error codes?ComputerScienceOne · Error Handling By Design
- How do you declare an enumerated type in C?ComputerScienceOne · Enumerated Types
- How can the return value communicate errors when roots are passed by reference?ComputerScienceOne · Quadratic Roots
- How can pass-by-reference parameters return both roots of a quadratic equation?ComputerScienceOne · Quadratic Roots
- What topics are covered in error handling?ComputerScienceOne · Function Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . .
- How can conditionals handle invalid inputs and special cases in a quadratic roots program?ComputerScienceOne · Quadratic Roots Revisited
- What are POSIX Error Codes?ComputerScienceOne · POSIX Error Codes