1

I am defining some macro - #define temporary inside code, which I have #undef after being used.

Is it not allowed to #undef MACRO?

void c_cmd(unsinged char *com)
{ 

int abc = com[0];
int res = 0;

switch(abc)
{
    case 1:
             #define ssCmd                 com[2]  /* SRT or STP*/
             res = abc + ssCmd;     
             /* part of some functionality */          

             #undef ssCmd 
             break;

    default:
             break;

}

}

Observed warning:

use of '#undef' is discouraged: 'ssCmd' [MISRA 2012 Rule 20.5, advisory]

Lundin
  • 195,001
  • 40
  • 254
  • 396
kapilddit
  • 1,729
  • 4
  • 26
  • 51
  • 1
    Simply read rule 20.5, it's self-explanatory. – Lundin Aug 27 '19 at 09:22
  • 2
    possible duplicate of [Why do the MISRA rules prohibit the use of '#undef'?](https://stackoverflow.com/questions/11665031/why-do-the-misra-rules-prohibit-the-use-of-undef) – P.W Aug 27 '19 at 09:23
  • 1
    @P.W Nah that post is outdated since MISRA-C:2012 had not been released. The rule about `#undef` was relaxed in 2012. – Lundin Aug 27 '19 at 09:24
  • related question - https://stackoverflow.com/questions/47769783/misra-c-2012-rule-20-5-undef-should-not-be-used – kapilddit Aug 27 '19 at 09:51
  • Use int ssCmd = com[2]; instead, and enclose the whole thing in {} to limit the scope of the variable. – Lars Ljung Aug 27 '19 at 16:59
  • Can I ask *why* you feel the need to `#define` and then `#undef` it? Remember that these are *compile time* directives not run time. And why not have the #define at the top of the file, and keep it? – Andrew May 25 '23 at 13:02

1 Answers1

2

Yes, MISRA Rule 20.5 says that #undef should not be used. It's an advisory rule.

Rationale:
The use of #undef can make it unclear which macros exist at a particular point within a translation unit.

Mike
  • 4,041
  • 6
  • 20
  • 37
  • 1
    Is the *"`#undef` should not normally be needed"* a quote from MISRA? I can't find this wording in the 2019 revision of MISRA C:2012. – AJM May 24 '23 at 14:24
  • Good point, try to make the wording clear. – Mike May 25 '23 at 05:09