C++: Why Use const?

Started by
32 comments, last by snk_kid 19 years, 5 months ago
Quite simply, why should I use it ever? What's it's reason for existance?
[s] [/s]
I can see the fnords.
Advertisement
Um...well, first reason: so things DON'T CHANGE. If you don't want things to change, you const them. Things can change other things sometimes, and if a filename gets accidentally changed (because of your bad coding practices), you'll wish you had constified it.

There's probably more, and I bet Oluseyi can point them out for you. He's smert smart.
Things change.
Also it takes up less memory.
one other thing is that the compiler can usually optimize better because it knows the intentions for a particular constant, eg. 'const int', rather than just 'int' tells the compiler that that identifier will never change, and maybe if you use it several times in a calculation, the compiler can keep it in a register etc. etc.

so basically, its to make things clearer to you AND the compiler.
"I am a donut! Ask not how many tris/batch, but rather how many batches/frame!" -- Matthias Wloka & Richard Huddy, (GDC, DirectX 9 Performance)

http://www.silvermace.com/ -- My personal website
Another useful use is passing variables by reference. You usually don't want to pass a Vector by value because of the copy overhead. But if you pass a Vector&, the called function can mess with it, which you may not want. So you pass it as a const Vector& - low overhead, and safe.

You can also declare member functions as constant, which means that the function won't change any of the member variables. The compiler can do some optimizations this way.

Also, you can safely call a const function on a const object or const object&. More generally, you build a 'chain of consts' that runs through your code and keeps you from modifying things you shouldn't. It's just good practice, and makes your code safer and more robust.
Quote:Original post by Boku San
There's probably more, and I bet Oluseyi can point them out for you. He's smert smart.
Thanks for the endorsement! [smile]

const indicates that the value contained/referred to by the variable can not be altered. In other words, it makes the variable non-mutable. This has many incarnations:
  • Simple constants, recommended as a replacement for preprocessor defines: const int PI = 3.142;

  • The type for references to literal values. If you want to be able to pass both a std::string and a string literal to a function, then you need a const std::string & parameter.

  • A qualifier for class methods indicating that they will & can not modify the object instance, making them permissible to call on const objects:

    class X
    {
    int retrieveSomethingOrOther(int param) const;
    };

One additional caveat to using const effectively is pointers. Consider the following:
const int * p = &someIntVariableconst int const * p2 = &someIntVariable
The first allows the modification of the value pointed to, but not the pointer itself. The second allows neither.
Quote:Original post by Roboguy
Also it takes up less memory.
Has anyone else heard of consts taking up less memory??
const takes up less memory in some cases because the compiler can make certain assumptions about the variable.
Can you go into more detail? Do you mean that if a const unsigned is equal to 3 then it might be replaced by unsigned short or something?
Than a non-const variable, particularly if it is, say, an int and the constants is known at compile-time. Instead of creating a variable holding, say, the value 42, it'll directly use 42 in the code. Like a macro in C, except better.

Also worth mentioning is that, since the compiler knows the constant is ... constant, it can apply optimizations it wouldn't if it didn't know that.

So, const can make your code faster.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement