Contents Up << >>

What is "const correctness"?

A good thing.

Const correctness uses the keyword "const" to ensure const objects don't get mutated. E.g., if function "f()" accepts a "String", and "f()" wants to promise not to change the "String", you:

can either pass by value: void f( String s ) /*...*/
or by constant reference: void f(const String& s ) /*...*/
or by constant pointer: void f(const String* sptr) /*...*/
but not by non-const ref: void f( String& s ) /*...*/
nor by non-const pointer: void f( String* sptr) /*...*/

Attempted changes to "s" within a fn that takes a "const String&" are flagged as compile-time errors; neither run-time space nor speed is degraded.

Declaring the "constness" of a parameter is just another form of type safety. It is almost as if a constant String, for example, "lost" its various mutative operations. If you find type safety helps you get systems correct (it does; especially in large systems), you'll find const correctness helps also.