Many existing functions that return an errno
error code are declared as returning a value of type int
. It is semantically unclear by looking at the function declaration or prototype if these functions return an error status or a value (or worse, some combination of the two).
TR 24731-1 defines a introduces the new type of errno_t
that is defined to be type int
in <errno.h>
and elsewhere. Many of the functions defined in TR 24731-1 return values of this type. As a matter of programming style, errno_t
should be used as the type of something that deals only with the values that might be found in errno
. For example, a function that returns the value of errno
should be declared as having the return type errno_t
.
...
This non-compliant code example illustrates a function called opener()
that returns errno
error codes. However, the function is declared as returning a value of type int
. The function, however, uses this return value to indicate the return status of the function by returning values of errno
. an int
. Consequently, the meaning of the return value is not as clear as it could be.
...
In this compliant solution, the opener()
function returns a value of type errno_t
, providing a clear indication that this function returns an errno
error code.
Code Block | ||
---|---|---|
| ||
#include <errno.h> enum { NO_FILE_POS_VALUES = 3 }; errno_t opener(FILE* file, int *width, int *height, int *data_offset) { int file_w; int file_h; int file_o; int rc; fpos_t offset; if (file == NULL) { return EINVAL; } if (fgetpos(file, &offset) != 0 ) { return errno; } if (fscanf(file, "%i %i %i", &file_w, &file_h, &file_o) != NO_FILE_POS_VALUES) { return EIO; } if (fsetpos(file, &offset) != 0 ) { return errno; } *width = file_w; *height = file_h; *data_offset = file_o; return 0; } |
...