Versions Compared

Key

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

...

This code calls the getc() function with an expression as an argument. If getc() is implemented as a macro, the file may be opened several times (see FIO31-C. Do not simultaneously open the same file multiple times).

Code Block
bgColor#ffcccc
const char const *filename = "test.txt"; 
FILE *fptr; 
 
int c = getc(fptr = fopen(filename, "r")); 

Compliant Solution: getc()

In this compliant solution, getc() is no longer called with an expression as its argument.

Code Block
bgColor#ccccff
const char const *filename = "test.txt"; 
FILE *fptr = fopen(filename, "r");
 
int c = getc(fptr); 

Non-Compliant Code Example: putc()

In this non-compliant example, putc() is called with c++ as an argument. If putc() is implemented as a macro, c++ could be evaluated several times within the macro expansion of putc() with unintended results.

Code Block
bgColor#ffcccc
const char const *filename = "test.txt";
FILE *fptr = fopen(filename, "w");

int c = 97;

while (c < 123) {
  putc(c++, fptr);
}

...

In the compliant solution, c++ is no longer an argument to putc().

Code Block
bgColor#ccccff
const char const *filename = "test.txt";
FILE *fptr = fopen(filename, "w");

int c = 97;

while (c < 123) {
  putc(c, fptr);
  c++;
}

...