tags:

views:

741

answers:

7

What are the advantages of const in C++ (and C) for the uninitiated?

exact duplicate of http://stackoverflow.com/questions/455518/how-many-and-which-are-the-uses-of-const-in-c

I beg to differ - while there are uses for const, the discussion is why use it. The question specified would be an interesting and substantive link, though.

+6  A: 

Seems pretty obvious - it keeps you from modifying things that shouldn't be modified.

Edit: for more guidance, always look to Herb Sutter.

Mark Ransom
...by accident. :-P const_cast can easily override.
Chris Jester-Young
I was just about to say the same thing.
Adam Peck
Though you should fear undefined behavior, if you use const_cast the wrong way...
sth
+6  A: 

When used as a const reference in a function, it lets the caller know that the thing being passed in won't be modified.

void f(Foo &foo, const Bar &bar) { ... }

In this case the caller will know that the foo might be modified, but the bar will not. The compiler will enforce this when compiling the body of f(), so that bar is never modified and never passed on to another function that might modify it.

All of the above safeguards can be bypassed using const_cast, which is why such a cast is considered "dangerous" (or at the very least, suspicious).

Greg Hewgill
+6  A: 

Const is particularly useful with pointers or references passed to a function--it's an instantly understandable API contract that the function won't change the passed object.

See also: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.4

DWright
+3  A: 

I'm not so convinced on the "safety" aspect of const (there's pros and cons)....however, what it does allow is certain syntax that you can't do without const

void blah(std::string& x)
{}

can only take a std::string object... However if you declare it const :-

void blah(const std::string& x) {}

you can now do

blah("hello");

which will call the appropriate constructor to make a std::string

Keith Nicholas
A: 

The contract aspect of const is also important to the compiler's optimizer. With certain const declarations, optimizations involving loop invariants are easier for the optimizer to spot. This is why const_cast is truly dangerous.

jmucchiello
The existance of const_cast and mutable explicitly *prevents* compilers from optimizing based on the const qualifiers.
Tom
A: 

You might find this useful StackOverFlow 455537

kal
+1  A: 

Also, by using const, you state your intention for the use of a variable or parameter. It is a good programming practice ("C/C++ Coding Style & Standards", item 2.3).

Also by avoiding using #define's to define constants and using const's, you increase the type-safety of your code. C++ Programming Practice Guidelines - item 2.1

Prembo