
It is undefined behavior to modify a value which is initially declared as const. const_cast can only be applied to pointers and references. It must be a pointer to const as shown below: const int x = 1 Ĭonst_cast can be used to take away the constness of a const object. We cannot create a regular pointer to a const object. We can say ptr is a constant pointer to constant integer. Neither the pointer nor the data object it points to. When const keyword appears on both the left and right sides of *. We can say ptr is a constant pointer to an integer.Ī const pointer must be initialized when it is declared.Ī constant pointer to a variable is useful for the storage that can be changed in value but not moved in memory. But we can modify the contents of the object to which it points. Here, we cannot modify the pointer to point to any other data item. When const keyword is on the right side of *. The pointer is not constantĬonstant pointer.

We can say ptr is a pointer to a constant integer. Here, the pointer can be modified to point to any other data item of appropriate type, but the data to which it points cannot be modified through this pointer. The following two lines does the same thing. When the const keyword is on the left side of *. With the const values, we can apply scope rules and class access specifiers like public, private etc.Ĭonst with pointers Non Constant pointer.



Max++ //compiler error What’s wrong with #define? We can declare constant variables (or more specifically ‘values’) by decorating them with const keyword as follows: const int Max = 256 //we must initialize it. But there are a lot more details about using this simple yet powerful keyword. One-liner: const is used to declare constants in C++.
