Versions Compared

Key

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

Do not invoke getc() or putc() or their wide-character analogues getwc() and putwc() with a stream argument that has side effects. The stream argument passed to these macros may be evaluated more than once if these functions are implemented as unsafe macros. (see See PRE31-C. Avoid side effects in arguments to unsafe macros for more information.).

This rule does not apply to the character argument in putc() or the wide-character argument in putwc(), which is guaranteed to be evaluated exactly once.

...

This noncompliant code example calls the getc() function with an expression as the stream argument. If getc() is implemented as a macro, the file may be opened multiple times. (see See FIO24-C. Do not open a file that is already open.).

Code Block
bgColor#ffcccc
langc
#include <stdio.h>
 
void func(const char *file_name) {
  FILE *fptr;

  int c = getc(fptr = fopen(file_name, "r"));
  if (feof(stdin) || ferror(stdin)) {
    /* Handle error */
  }

  if (fclose(fptr) == EOF) {
    /* Handle error */
  }
}

...

NOTE: The output of this compliant solution differs depending on the character set. For example, when run on a machine using an ASCII-derived code set such as ISO-8859 or Unicode, this solution will print out the 26 lowercase letters of the English alphabet. However, if run with an EBCDIC-based code set, such as Codepage 037 or Codepage 285, punctuation marks or symbols may be output between the letters.

...