| Data Structures and Algorithms |
| Errors in C ADTs |
What can we do in C?
Often there will be a value of the function return which
can be used for indicating an error condition.
Constructors return pointers to blocks of memory allocated for
the object:
a null pointer indicates an error.
int f( ... ) {
X a;
a = ConsX( ... );
if ( a != NULL ) {
/* No error */
....
return 1;
}
else
{
/* return an error value to the next level up */
return 0;
}
}
/* vector.h */
typedef struct vector_t *vector;
typedef enum( NoError, SizeMisMatch, NoMemory, InvalidVector )
vector_error;
double AddVector( vector a, vector b, int *error );
The implementation:
#include "vector.h"
double DotProduct( vector a, vector b, vector_error *error ) {
if ( LengthVector(a) == LengthVector(b) )
{
....
}
else
{
*error = SizeMisMatch;
return 0.0;
}
}
This solution, while achieving the aim of robust code,
would probably be considered too cumbersome.
The additional argument also adds to the execution time.
|
Continue on to C Errors (emulating an
exception mechanism) Back to the Table of Contents |