Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This non-compliant code example illustrates a function called opener() that 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. Consequently, the meaning of the return value is not as clear as it could be.

Code Block
bgColor#FFCCCC

enum { NO_FILE_POS_VALUES = 3 };

int opener(FILE* file, int *width, int *height, int *data_offset) {
  int file_w;
  int file_h;
  int file_o;
  fpos_t offset;

  if (file == NULL) { return -1; }
  if (fgetpos(file, &offset) != 0) { return -1; }
  if (fscanf(file, "%i %i %i", &file_w, &file_h, &file_o)  != 3NO_FILE_POS_VALUES) { return -1; }
  if (fsetpos(file, &offset) != 0) { return -1; }

  *width = file_w;
  *height = file_h;
  *data_offset = file_o;

  return 0; 
}

...

In this compliant solution, the opener() function returns a value of type errno_t providing a clear indication that this returns a values that might be found in errno.

Code Block
bgColor#ccccff
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 ((rc = fgetpos(file, &offset)) != 0 ) { return rc; }
  if (fscanf(file, "%i %i %i", &file_w, &file_h, &file_o)  != 3NO_FILE_POS_VALUES) { return EIO; }
  if ((rc = fsetpos(file, &offset)) != 0 ) { return rc; }
 
  *width = file_w;
  *height = file_h;
  *data_offset = file_o;

  return 0; 
}

...