Reasons to use const are best summarised here:
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.7
There are cases where the const will use more memory, there are cases
where the #define will be worse.
Yet no such cases -should- exist.
In other words, the choice between a const int variable or the
equivalent #define constant in a C++ should make no difference to
either the program's memory use or its performance. And if there is a
case where choosing between the two ways to specify a constant value -
really does have an effect on a compiled C++ program, then either it's
time to find a decent C++ compiler or to fix a hidden dependency bug
in the program.
Logically, if we compile the same program twice and produce two
builds, would we expect to find that one of the builds has better
performance or uses less memory than the other? Probably not. And yet,
that is exactly the situation described here: How after all, does
simply "replacing" an integer constant with the same integer constant
value do anything to change the program's logic? What will the program
do differently afterwards than it did before? (Nothing different, we
would hope). So, with no change to the program's logic, the program
built after the change is the same program - so there is no reason to
expect a different binary than the one build before.
In practice, there are no runtime benefits to be realized from using
#define constants instead of C++'s (better) alternatives. Consider
this code I copied from some else's post to this thread:
int const foo = 4;
#define FOO 4
void bar()
{
std::vector<int> v;
v.push_back(foo);
v.push_back(FOO); //will translate to v.push_back(int(FOO));
v.push_back(foo);
v.push_back(FOO); //a second temporary will be allocated
}
When optimizing bar(), gcc transforms its body into a loop - this loop
iterates four times and executes the same instruction (an immediate
store of the value "4" directly into the vector's storage) each time.
So an example meant to highlight the differences between the two types
of constants - can also be used to demonstrate that that whatever
their semantic differences might be - as far as this C++ program is
concerned, the four push_backs() statements really all do the same
thing.
Greg