What is the difference between define and const in C++?
In C++, both #define and const can be used to define constants, but they have some important differences.
- #define is a preprocessor directive that is processed before compiling and does not perform type checking. It merely replaces identifiers with text. On the other hand, const is a keyword that undergoes type checking during compilation to ensure the correctness of the constant’s type.
- #define can be used to define constants of any type, including strings and functions, while const can only be used to define constant variables.
- Constants defined with #define have no scope restrictions and are global. On the other hand, constants defined with const are scoped and only visible within the scope where they are defined.
- #define does not allocate memory, while const allocates memory and maintains the value of the constant throughout the program’s lifespan.
- #define can be used anywhere, including inside functions, while const can only be used in global scope or namespace scope.
In conclusion, const is a safer and more controlled way to define constants, providing better type checking and scope limitations. In modern C++, it is recommended to use const for defining constants and to avoid using #define as much as possible.