The const_cast operator in C++ is used to add or remove the const qualifier from a variable. This can be useful when you need to pass a const variable to a function that expects a non-const parameter. However, it should be used with caution, as modifying a const variable after casting away its const qualifier results in undefined behavior.
Syntax:
const_cast<new_type>(expression)
Example:
`void func(int* p) { *p = 10; }
int main() { const int a = 5; func(const_cast<int*>(&a)); // Undefined behavior if func modifies a return 0; }`
A const value is a variable whose value cannot be changed after initialization. This is useful for defining constants and ensuring that certain variables remain immutable throughout the program.
Example:
const int x = 10;
x = 20; // Error: assignment of read-only variable 'x'
There are several variations of const pointers, each with different meanings:
const Data:
const and cannot be modified through the pointer.Syntax:
const int* ptr;
Example:
int a = 10;
int b = 20;
const int* ptr = &a;
*ptr = 30; // Error: cannot modify const int
ptr = &b; // Allowed: pointer can point to another address
const Pointer to Data:
const and cannot be changed to point to another address.