I was asked this question in a technical interview:
What is the difference between a
constand a macro in C++?
My answer was that a macro is a preprocessor directive and it could be difficult to debug the application if you use a macro since it is replaced with the constant expression before compilation, whereas a const can have a type identifier and is easy to debug.
Could anyone point out any other difference and which should be preferred?
EDIT:
From the IBM documentation for C++:
The following are some differences between
#defineand theconsttype qualifier:
The
#definedirective can be used to create a name for a numerical, character, or string constant, whereas a const object of any type can be declared.A const object is subject to the scoping rules for variables, whereas a constant created using
#defineis not. Unlike aconstobject, the value of a macro does not appear in the intermediate source code used by the compiler because they are expanded inline. The inline expansion makes the macro value unavailable to the debugger.A macro can be used in a constant expression, such as an array bound, whereas a
constobject cannot. (I think we surely need to use macro to definearray_size.The compiler does not type-check a macro, including macro arguments.