Re: "#define" vs "const int"
In article <gje3hn0ec0@news2.newsguy.com>,
Bill <Bill_NOSPAM@comcast.net> wrote:
"Eric" <answer.to.newsgroup@nospam.com> wrote in message
news:k3ekl4t4hlh4odpm2d7cfsrmfi1b3s3qhi@4ax.com...
I'm told that with most optimizing compilers, if you say "const int
foo = 4" rather than "#define foo 4", the compiler won't actually
allocate any memory for the int. True?
No one mentioned (I think) that #define is a "pre-processor directive".
The substitution of "4" for "foo" is made before the "real compilation" even
starts. Hence, no bytes for foo!
Hmm, technically correct about "foo" itself. However, the amount of memory
used by the program might be higher with the #define depending on how
it is later used. E.g. (already hinted by James)
#include <vector>
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
}
This is even worse:
#include <string>
#include <vector>
std::string const foo = "this a a constant string";
#define FOO "this is a macro string"
void bar()
{
std::vector<std::string> v;
v.push_back(foo);
v.push_back(FOO); //i.e. v.push_back(std::string(FOO));
v.push_back(foo);
v.push_back(FOO); //a second temporary will be allocated
}
Yan