Bifalgorithm post · Computer science one · Using Enumerated Types for Error Codes

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

How can enumerated types be used for error codes in C? (Computer science one · Using Enumerated Types for Error Codes) — "19.4. Using Enumerated Types for Erro…

Ideas in this flowchart

  • Uso de tipos enumerados para los códigos de error
  • Se define el tipo enumerado ErrorCode para representar los resultados de quadraticRoots().
  • NO_ERROR tiene el valor cero por convención.
  • DIV_BY_ZERO_ERROR representa la división por cero.
  • COMPLEX_ROOT_ERROR representa raíces complejas.
  • NULL_POINTER_ERROR representa punteros nulos.
  • La función quadraticRoots() devuelve un valor de tipo ErrorCode.
  • La función recibe a, b, c y punteros para almacenar root1 y root2.
  • La función verifica las condiciones de error antes de calcular las raíces.
  • Si a es igual a cero, devuelve DIV_BY_ZERO_ERROR.
  • Si el discriminante es negativo, devuelve COMPLEX_ROOT_ERROR.
  • Si root1 o root2 es NULL, devuelve NULL_POINTER_ERROR.
  • Si no ocurre ningún error, continúa con el cálculo de las raíces.
  • Calcula el discriminante y asigna las dos raíces mediante root1 y root2.
  • Después de un cálculo exitoso, devuelve NO_ERROR.
Feed/

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

No cover

Channel

Computer science one

1 page

"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}"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.