Sign in to follow this  
Tradone

Why use const?

Recommended Posts

Guest Anonymous Poster
Mammal Dog

is allocating memory for the object on the call stack of the function that you are doing it in.

Dog = new Mammal is allocating memory from the heap and will return to you a pointer to that heap memory address. The actual syntax for this operation is.

Mammal* Dog = new Mammal

Share this post


Link to post
Share on other sites
Use const when the value will never change:
Quote:
const int FPSLimit = 60;

When you use 'new', you must delete it, because it is created at runtime instead of compile-time:
Quote:
Baddy = new Enemy;
...
delete Baddy;

Share this post


Link to post
Share on other sites
Take a look at this page for information on 'const'. For 'const correctness', take a look at this page. Hopefully between those two pages your first question will be answered.

On the issue of pointers, take a look at this page to learn about them. GameDev has an article you might want to check out as well here. It ties in the why you would want to use pointers in games and such. Between those two pages, hopefully your second question will be answered [smile]

Share this post


Link to post
Share on other sites
Quote:
Original post by oscinis
When you use 'new', you must delete it, because it is created at runtime instead of compile-time:


This is not true. "Mammal Dog" is not created at compile time. It is created while the function is executing at run-time. It is destroyed before the function returns to the calling function. If "Mammal Dog" is written outside a function, Dog is created before main() is run and destroyed after exiting main().

The difference is that "new Mammal" is created on the heap wherease "Mammal Dog" is created either on the stack (when in a function) or in a data segment (when declared at file-scope). And if you allocate it on the heap, yes you are correct, you should delete it.

Share this post


Link to post
Share on other sites
Const is good but can be hell if it isn’t used throughout the hole project.

Declaring a variable const lets the compiler do optimizations. It doesn’t need to get the value from the source. So if it the same value stored closer it can use it instead. There is also something called Volatile its not the exact opposite but almost.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this