Versions Compared

Key

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

...

Code Block
bgColor#ffcccc
char *file_name;
FILE *fptr = NULL;

/* initializeInitialize file_name */

int c = 'a';
while (c <= 'z') {
  if (putc(c++, fptr ? fptr :
       (fptr = fopen(file_name, "w")) == EOF) {
    /* Handle error */
  }
}

...

Code Block
bgColor#ccccff
char *file_name;

/* initializeInitialize file_name */

FILE *fptr = fopen(file_name, "w");
if (fptr == NULL) {
  /* Handle error */
}

int c = 'a';

while (c <= 'z') {
  if (putc(c++, fptr) == EOF) {
    /* Handle error */
  }
}

The c++ is perfectly safe, because putc() guarantees to evaluate its character argument exactly once.

This example shows only shows the side-effect issue. The output differs depending on the character set. Consequently, it is important to not make assumptions about the order of the letters. For example, when run on a machine using an ASCII-derived code set such as ISO-8859 or Unicode, this code sample will print out the 26 lower case 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.

...