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

How can enumerated types be used for error codes in C? | ComputerScienceOne | Bifalgorithm | Bifalgorithm