The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.
Primary constants − Integer, float, and character are called as Primary constants. Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants.
Use of the Constants in C It has two major categories- primary and secondary constants. Character constants, real constants, and integer constants, etc., are types of primary constants.
We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized. Using const has a very big benefit. For example, if you have a constant value of the value of PI, you wouldn't like any part of the program to modify that value.
Trying to collect some uses:
Binding some temporary to reference-to-const, to lengthen its lifetime. The reference can be a base - and the destructor of it doesn't need to be virtual - the right destructor is still called:
ScopeGuard const& guard = MakeGuard(&cleanUpFunction);
Explanation, using code:
struct ScopeGuard {
~ScopeGuard() { } // not virtual
};
template<typename T> struct Derived : ScopeGuard {
T t;
Derived(T t):t(t) { }
~Derived() {
t(); // call function
}
};
template<typename T> Derived<T> MakeGuard(T t) { return Derived<T>(t); }
This trick is used in Alexandrescu's ScopeGuard utility class. Once the temporary goes out of scope, the destructor of Derived is called correctly. The above code misses some small details, but that's the big deal with it.
Use const to tell others methods won't change the logical state of this object.
struct SmartPtr {
int getCopies() const { return mCopiesMade; }
};
Use const for copy-on-write classes, to make the compiler help you to decide when and when not you need to copy.
struct MyString {
char * getData() { /* copy: caller might write */ return mData; }
char const* getData() const { return mData; }
};
Explanation: You might want to share data when you copy something as long as the data of the originally and the copie'd object remain the same. Once one of the object changes data, you however need now two versions: One for the original, and one for the copy. That is, you copy on a write to either object, so that they now both have their own version.
Using code:
int main() {
string const a = "1234";
string const b = a;
// outputs the same address for COW strings
cout << (void*)&a[0] << ", " << (void*)&b[0];
}
The above snippet prints the same address on my GCC, because the used C++ library implements a copy-on-write std::string
. Both strings, even though they are distinct objects, share the same memory for their string data. Making b
non-const will prefer the non-const version of the operator[]
and GCC will create a copy of the backing memory buffer, because we could change it and it must not affect the data of a
!
int main() {
string const a = "1234";
string b = a;
// outputs different addresses!
cout << (void*)&a[0] << ", " << (void*)&b[0];
}
For the copy-constructor to make copies from const objects and temporaries:
struct MyClass {
MyClass(MyClass const& that) { /* make copy of that */ }
};
For making constants that trivially can't change
double const PI = 3.1415;
For passing arbitrary objects by reference instead of by value - to prevent possibly expensive or impossible by-value passing
void PrintIt(Object const& obj) {
// ...
}
There are really 2 main uses of const in C++.
Const values
If a value is in the form of a variable, member, or parameter that will not (or should not) be altered during its lifetime you should mark it const. This helps prevent mutations on the object. For instance, in the following function I do not need to change the Student instance passed so I mark it const.
void PrintStudent(const Student& student) {
cout << student.GetName();
}
As to why you would do this. It's much easier to reason about an algorithm if you know that the underlying data cannot change. "const" helps, but does not guarantee this will be achieved.
Obviously, printing data to cout does not require much thought :)
Marking a member method as const
In the previous example I marked Student as const. But how did C++ know that calling the GetName() method on student would not mutate the object? The answer is that the method was marked as const.
class Student {
public:
string GetName() const { ... }
};
Marking a method "const" does 2 things. Primarily it tells C++ that this method will not mutate my object. The second thing is that all member variables will now be treated as if they were marked as const. This helps but does not prevent you from modifying the instance of your class.
This is an extremely simple example but hopefully it will help answer your questions.
Take care to understand the difference between these 4 declarations:
The following 2 declarations are identical semantically. You can change where ccp1 and ccp2 point, but you can't change the thing they're pointing at.
const char* ccp1;
char const* ccp2;
Next, the pointer is const, so to be meaningful it must be initialised to point to something. You can't make it point to something else, however the thing it points to can be changed.
char* const cpc = &something_possibly_not_const;
Finally, we combine the two - so the thing being pointed at cannot be modified, and the pointer cannot point to anywhere else.
const char* const ccpc = &const_obj;
The clockwise spiral rule can help untangle a declaration http://c-faq.com/decl/spiral.anderson.html
As a little note, as I read here, it's useful to notice that
const
applies to whatever is on its immediate left (other than if there is nothing there in which case it applies to whatever is its immediate right).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With