MainID
MainID

Reputation: 30064

Why to undefine macros before define them?

#undef GOOGLE_LONGLONG
#undef GOOGLE_ULONGLONG
#undef GOOGLE_LL_FORMAT

#ifdef _MSC_VER
#define GOOGLE_LONGLONG(x) x##I64
#define GOOGLE_ULONGLONG(x) x##UI64
#define GOOGLE_LL_FORMAT "I64"  // As in printf("%I64d", ...)
#else
#define GOOGLE_LONGLONG(x) x##LL
#define GOOGLE_ULONGLONG(x) x##ULL
#define GOOGLE_LL_FORMAT "ll"  // As in "%lld". Note that "q" is poor form also.
#endif

Why do this and when to do such things?

Upvotes: 2

Views: 647

Answers (4)

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95569

Generally this is a bad idea. Ironically, given that you have "Google" in your symbol names, you might be curious to know that Google's C++ Style Guide urges against undefining macros before defining them. Basically, if you define a macro multiple times, you will get an error. The undef prevents these errors, which can suppress some alarm bells that probably should be going off. There are a few cases where an undef makes sense, such as in defining assert where the behavior of the macro can be different each time you include the header (based on whether some other macro is defined). If the macro should have a single value for the entire program, though, this undef doesn't make any sense.

Upvotes: 4

Shaggy Frog
Shaggy Frog

Reputation: 27601

To make sure they haven't been somehow defined already. Otherwise, the preprocessor may give warnings/errors when it redefines them a second time.

Upvotes: 0

liaK
liaK

Reputation: 11648

Also in such cases where the values will be different but the variable remains the same.

For e.g

#define pi 3.1456

and down the lane you might just need pi as 3.14. So what you can do is,

#undef pi
#define pi 3.14

From an example here,

Any occurrences of the identifiers that follow these #undef directives are not replaced with any replacement tokens. Once the definition of a macro has been removed by an #undef directive, the identifier can be used in a new #define directive.

Upvotes: 0

Ankur Mukherjee
Ankur Mukherjee

Reputation: 3867

Its just for the sake of security or we can say for the sake of precautions that we undefine macros before defining them,so that the compiler will not show any warning/errors on redefining them

Upvotes: 2

Related Questions