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

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

+6
source share
3 answers

Basically, since MISRA is too paranoid and does not trust programmers to know what they are doing :-) Seriously, MISRA tries to prevent certain errors and is guided by the belief that if you prohibit potentially problematic code constructs, the reliability of the software suddenly increases. Is this a matter of debate? In the case of #undef probable reason is that, once a macro is defined, its extension remains positive and always matches its definition. If you enable #undef , the identifier can be reused as a variable, function name, typedef or member of a structure / union, or even as a macro with a, gasp, a different extension. This is a way to prevent identifier shadowing if you like. Scary, isn't it ?! You decide!

To answer the second question, the only way to limit the scope of the macro if #undef cannot be used is to use the end of the file, which is the only other standard way that allows you to complete the scope of the macro. In other words, you need to split the source files into smaller ones and define the macro only when compiling a specific file where necessary.

+7
source

MISRA has its own explanation of why the use of #undef prohibited:

#undef is usually not required. Its use can lead to confusion regarding the existence or value of a macro when it is used in code.

+5
source

In response to the @Bubble comment above:

I ask you to give an example. I can not imagine how this can create confusion?

Imagine the script ...

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

And then someone comes in and inserts between existing MACRO calls

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

The original second MACRO call will not do what you expected!

+2
source

Source: https://habr.com/ru/post/921374/


All Articles