Monday 7 November 2011

Using a Null Pointer As an Error Value in C programming

Using a Null Pointer As an Error Value

The second way the null pointer can be used is as an error value. Many C functions return a pointer to some
object. If so, the common convention is to return a null pointer as an error code:
if ( setlocale( cat, loc_p ) == NULL )

{
/* setlocale() failed; do something */
/* ... */
}
This can be a little confusing. Functions that return pointers almost always return a valid pointer (one that
doesn’t compare equal to zero) on success, and a null pointer (one that compares equal to zero) pointer on
failure. Other functions return an int to show success or failure; typically, zero is success and nonzero is
failure. That way, a “true” return value means “do some error handling”:

if ( raise( sig ) != 0 ) {
/* raise() failed; do something */
/* ... */
}

The success and failure return values make sense one way for functions that return ints, and another for
functions that return pointers. Other functions might return a count on success, and either zero or some
negative value on failure. As with taking medicine, you should read the instructions first.

No comments:

Post a Comment