Sanyam Goel
Sanyam Goel

Reputation: 2180

Why CERT standard PRE00-CPP says "Avoid defining macros"

According to the CERT standards Object-like macros can be dangerous because their uses are not subject to the language scope rules. Can any one please explain with an example How it is problematic. say for example I have an Object-like macro #define BUFFER_SIZE 1024

Upvotes: 1

Views: 214

Answers (3)

Mats Petersson
Mats Petersson

Reputation: 129454

A classic example is

#define max 1234

...
class A
{
   int arr[100];
 public:
      ...
   int max() { ... find highest in arr ... }
};

This won't compile.

Upvotes: 3

nikolas
nikolas

Reputation: 8975

// file a.hpp
#define SOME_MACRO 42

// file some/nested/dir/really/far/in/x.hpp
#define SOME_MACRO 13

Kaboom. This would have easily been avoided using any kind of scope, e.g.

struct X { static unsigned const value = 42; };
struct Y { static unsigned const value = 13; };

Now you can access X::value and Y::value. Same goes for namespaces:

namespace a { struct X; }
namespace b { struct X; }

Upvotes: 5

user2249683
user2249683

Reputation:

C/C++ preprocessing is just manipulating/generating text, no language rules involved.

Upvotes: 3

Related Questions