I wanted to know the advantage of consts over macros. And I found the line "The main disadvantage of macro is it doesn't do type checking.". Is it not an advantage of macro? So that I can #define any constants without a limit. Can you pls explain me why it is said as a disadvantage?

Recommended Answers

All 2 Replies

Typing is good, it allows the compiler to enforce its type restriction. That's good by the way.

So that I can #define any constants without a limit.

There's still a limit. For a symbolic constant you're deferring type checking until after preprocessing. The disadvantage of this is that the original source code doesn't match the intermediate code being checked. Any warnings or errors coming from use of the macro will likely be confusing because of that disconnect.

However, for simple macros that could alternatively be defined as const objects, the problem of confusing bugs isn't as prominent. The macro's symbol does go away and won't likely be mentioned in diagnostic messages, but a simple macro is easier to figure out than a macro for more a complex expression.

The big difference between const and #define for symbolic constants is #define produces a true compile-time constant. const objects are not constant enough to be used as array sizes (think "read-only" instead of "constant"), which is one of the most common use cases for #define.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.