Archived

This topic is now archived and is closed to further replies.

C++ const/#define

This topic is 5130 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok, I prefer const to #define and inline over #define for small functions. But is doesn''t const take up memory for the variables? I''m converting an emulator I wrote in C to C++ and I have a lot of #defines that I want to convert to const blah = blah. I was just wondering if the memory issue would crop up at any stage. Also is there any performance hit in using const over #define, or inline over #define. I know some inline funcs are expanded by the compiler in some cases so will that degrade the performance at all? Thanks in advance.

Share this post


Link to post
Share on other sites
> But is doesn''t const take up memory for the variables?
No.

> Also is there any performance hit in using const over #define...
No.

> ...or inline over #define.
No. However, there can be a performance hit in using #define over inline. If a function''s code is replicated everywhere, you''ll get more cache misses, which cost more than a function call. Use inline and let the compiler decide.

Share this post


Link to post
Share on other sites
Hello stew,

const can take up memory, depends on how it is use.
most compilers if the constant is not extrenly link or the address of it is not taken. It will use it as a it was like a #define.
with that being said the value still has to be store some were so the program can use it. with a define the value was stuck right there were the define was used. If you got a smart compile/link might be able to combine into one address. But if not sure use a const decleared in header and defined in a source file.
That way your gaurantee that space is alloctaed once.

I would still try to use const or enum for all non changabe values.
const floats/double for real numbers
and enum's for int types(short, int, long).

Lord Bart

[edited by - lord bart on November 29, 2003 9:51:50 AM]

Share this post


Link to post
Share on other sites