14

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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
casualcoder
  • 4,770
  • 6
  • 29
  • 35
  • 1
    I think this is an exact duplicate of http://stackoverflow.com/questions/455518/how-many-and-which-are-the-uses-of-const-in-c – ChrisW Jan 22 '09 at 03:01
  • 1
    You might find this useful [StackOverFlow 455537](http://stackoverflow.com/questions/455518/how-many-and-which-are-the-uses-of-const-in-c#455537) – kal Jan 22 '09 at 04:02

6 Answers6

12

Const is particularly useful with pointers or references passed to a function--it's an instantly understandable "API contract" of sorts 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
  • 9,258
  • 4
  • 36
  • 53
11

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
  • 951,095
  • 183
  • 1,149
  • 1,285
6

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
  • 299,747
  • 42
  • 398
  • 622
5

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
  • 43,549
  • 15
  • 93
  • 156
5

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
  • 2,256
  • 2
  • 30
  • 50
-1

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
  • 18,754
  • 7
  • 41
  • 61
  • 2
    The existance of const_cast and mutable explicitly *prevents* compilers from optimizing based on the const qualifiers. – Tom Jan 22 '09 at 04:33