MISRA Discussion Forums
Rule 2.1 : Checking for all possible error status - Is a deviation reasonable for this? - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4)
+--- Forum: MISRA C:2012 and MISRA C:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=21)
+---- Forum: 8.2 Unused code (https://forum.misra.org.uk/forumdisplay.php?fid=157)
+---- Thread: Rule 2.1 : Checking for all possible error status - Is a deviation reasonable for this? (/showthread.php?tid=1456)



Rule 2.1 : Checking for all possible error status - Is a deviation reasonable for this? - guru72 - 19-09-2018

Hello,
I have the following piece of code for which I get a MISRA Rule 2.1 error. I am considering a deviation for this - All possible error status from a function call can be checked even if the function does not return all possible error statuses. Can you please provide feedback on if this is a reasonable deviation?

(Btw, this is my first post - please feel free to let me know if this is outside the scope here)

Example:

Code:
#include "stdafx.h"
typedef enum ErrStatus {
    Success = 0,
    Err_1,
    Err_2
} ErrStatus;

ErrStatus f(int x) {
    if (x < 0) {
        return Err_1;
    }
    else
    {
        return Success;
    }
}

    int main()
    {
        ErrStatus x = f(5);
        switch (x)
        {
        case Err_1:
            printf("err 1"); break;
        case Err_2:
            printf("err 2 "); break;  /* Is this dead code ? */
        default:
            printf("Success"); break;
        }
    }



Re: Rule 2.1 : Checking for all possible error status - Is a deviation reasonable for this? - misra-c - 04-10-2018

The example correctly produces a rule 2.1 violation as it can be determined that "x" will never have the value of "Err_2". A deeper analysis tool might also give a violation on "Err_1" since the value returned by f(5) will always have the value of "Success".

The proposed deviation is not sufficent as stated as there is nothing to prevent a compiler from "optimising" away the code for "Err_1" and "Err_2" cases. Instead the switch chooser should be accessed by means of a volatile qualified lvalue. For example
Code:
switch ( *( volatile ErrStatus * ) &x )
This makes the code compliant with this rule AND prevents the case branches being optimised away by the compiler.

When writing a deviation you should read the MISRA Compliance document which can be found at https://tinyurl.com/MisraCompliance.
With respect to this question you should consider the advice given in the MISRA C:2004 14.1 B.1 permit of the "MISRA C 2004 Permits" document, which can be found at https://tinyurl.com/MisraPermits2004. This document was written for MISRA-C:2004, but advice given in this permit is relevant to MISRA C:2012.