Main Content

MISRA C++:2008 Rule 16-0-2

Macros shall only be #define 'd or #undef 'd in the global namespace

Description

Rule Definition

Macros shall only be #define 'd or #undef 'd in the global namespace.

Rationale

If you define or undefine macros in a local namespace, you might expect the macro to be valid only in the local namespace. But macros do not follow the scoping mechanism. Instead, the compiler replaces all occurrences of a macro by its defined value beginning at the #define statement until the end of file or until the macro is redefined. This behavior of macros might be contrary to developer expectation and might cause logic errors that result in bugs.

Polyspace Implementation

Polyspace® flags a #define or #undef statement that is placed within a block instead of in the global namespace.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include<cstdlib>
#define HCUT 1
namespace unnormalized{
	#define HCUT 6582 //Noncompliant
	void foo(){
		//...
	}
};
void bar(){
	int intEnergy = HCUT*10; 
	//HCUT is 6582, you might expect HCUT=1;
}

namespace uniteV{
	const double hcut = 6582; //eV
	void foo(){
		
	}
};

In this example, different values of HCUT are defined, perhaps to accommodate code written by using different systems of unit. You might expect the definition of HCUT in the namespace unnormalized to remain limited to the namespace. But the value of HCUT remains 6582 until the end of file. For instance, in the function bar, you might expect that HCUT is one, but the value of HCUT remains 6582, which might cause logic error, unexpected results, and bugs. Polyspace flags the #define statement within the local namespace.

To implement constants that might have different values in different scopes, use const variables, as shown in the namespace uniteV. Avoid using macros to represent constants that might require different values in different scopes.

Check Information

Group: Preprocessing Directives
Category: Required

Version History

Introduced in R2013b