...
| Code Block | ||
|---|---|---|
| ||
FILE *fptr;
int c = getc(fptr = fopen(file_name, "r"));
if (c == EOF) {
/* Handle Error */
}
|
This non-compliant code example also violaties FIO33-C. Detect and handle input output errors resulting in undefined behavior.
...
| Code Block | ||
|---|---|---|
| ||
FILE *fptr; int c; if ((fptr = fopen(file_name, "r")); if (fptr == NULL) { /* Handle Error */ } intif ((c = getc(fptr);)) == EOF) { /* Handle Error */ } |
Non-Compliant Code Example: putc()
...
| Code Block | ||
|---|---|---|
| ||
FILE *fptr = NULL;
int c = 'a';
while (c <= 'z') {
putc(c++, fptr ? fptr : (fptr = fopen(file_name, "w"));
}
|
If the putc() macro does evaluate evaluates its stream argument 2 or more multiple times, this might still seem safe, as the ?: operator ostensibly prevents multiple calls to fopen(). However, there is no guarantee that these would happen in distinct sequence points. So Consequently this coode might code also violate violates EXP30-C. Do not depend on order of evaluation between sequence points.
...
| Code Block | ||
|---|---|---|
| ||
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, since because putc() guarantees to evaluate its character argument exactly once.
This example only illustrates the side-effect issue. The output will differ differs depending on the character set.
...