Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

misra

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?

like image 576
bubble Avatar asked Jul 26 '12 08:07

bubble


2 Answers

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.

like image 109
Jens Avatar answered Sep 28 '22 16:09

Jens


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.

like image 33
ouah Avatar answered Sep 28 '22 17:09

ouah