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

梦想与她 提交于 2019-12-23 09:04:29


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?


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.


MISRA has its own explanation on why the usage of #undef is banned:

#undef should normally not be needed. Its use can lead to confusion with respect to the existence or meaning of a macro when it is used in the code.


In reply to @Bubble's comment above:

Requesting you to give an example on this. I can't imagine how it can create confusion ?

Imagine the scenario...

#define MACRO some-definition
MACRO // Invovation 1
MACRO // Invocation 2

And then someone comes along and inserts, between the existing invocations of MACRO

#undef MACRO
#define MACRO something-else
MACRO // Between (1) and (2)

The original second invocation of MACRO will not do what you expected!