What is the difference between #define and const Keyword in C++?

C++Server Side ProgrammingProgramming Scripts

The #define directive is a preprocessor directive; the preprocessor replaces those macros by their body before the compiler even sees it. Think of it as an automatic search and replace of your source code.

A const variable declaration declares an actual variable in the language, which you can use like a real variable: take its address, pass it around, cast it, convert it, etc.

Without compiler optimizations, there is a hidden cost of memory allocation associated with both of these in different cases. But with proper optimizations they are more or less the same. Also, preprocessor macros don't have any scope, while const values do.

Published on 15-Feb-2018 18:55:24