Search code examples
cmisra

Why do the MISRA rules prohibit the use of '#undef'?


Why do the MISRA rules prohibit the use of #undef in a program? If I want to limit the scope of any macro, how to do it without using #undef?


Solution

  • Basically, because MISRA is too paranoid and doesn't trust programmers to know what they are doing :-) Seriously, MISRA tries to prevent certain errors and is guided by the belief that if you forbid potentially problematic code constructs, reliability of software suddenly increases. Whether that is true is a matter of debate. In the case of #undef, the likely reason is that once a macro is defined, its expansion stays put and is always that from its definiton. If you allow #undef, the identifier could be reused as a variable, function name, typedef or struct/union member, or even as a macro with a, gasp, different expansion. It's some way to prevent identifier shadowing, if you will. Scary, isn't it?! You decide!

    To answer your second question, the only way to limit the scope of a macro if #undef can't be used is to use the end-of-file, which is the only other standard defined way to end the scope of a macro. In other words, you have to split up your source files into smaller ones and define the macro only when compiling the particular file where it is needed.