MISRA C:2012 Rule 22.7

The macro EOF shall only be compared with the unmodified return value from any Standard Library function capable of returning EOF

Description

Rule Definition

The macro EOF shall only be compared with the unmodified return value from any Standard Library function capable of returning EOF.

This rule comes from MISRA C®: 2012 Amendment 1.

Rationale

The EOF value may become indistinguishable from a valid character code if the value returned is converted to another type. In such cases, testing the converted value against EOF will not reliably identify if the end of the file has been reached or if an error has occurred.

Troubleshooting

If you expect a rule violation but do not see it, refer to the documentation of Polyspace® Bug Finder™ or Polyspace Bug Finder Server™.

Examples

expand all

#include <stdio.h>
#include <stdint.h>

void f1(void)
{
    char ch;
    ch = (char) getchar();
    if (EOF != (int32_t) ch) {    /* Non-compliant */
    }
}

void f2(void)
{
    char ch;
    ch = (char) getchar();
    if (!feof(stdin)) {           /* Compliant */
    }
}

void f3(void)
{
    int32_t i_ch;
    i_ch = getchar();
    if (EOF != i_ch) {            /* Compliant */
        char ch;
        ch = (char) i_ch;
    }
}

In this example:

  • The test in the f1 function is non-compliant. It will not be reliable as the return value is cast to a narrower type before checking for EOF.

  • The test in the f2 function is compliant. It shows how feof() can be used to check for EOF when the return value from getchar() has been subjected to type conversion.

  • The test in the f3 function is compliant. It is reliable as the unconverted return value is used when checking for EOF.

Check Information

Group: Resources
Category: Required
AGC Category: Required
Introduced in R2017a