#include #include // For strlen and strcpy // An example of an "old C function" that expects a char* for modification // even if it might not always modify it. void process_string(char* str) { if (str != nullptr) { std::cout << "Processing string: " << str << std::endl; // Simulate a modification if needed if (strlen(str) > 0) { str[0] = toupper(str[0]); // Modify the first character } } } int main() { // Case 1: Modifying a non-const string through a const pointer char buffer[50] = "hello world"; const char* const_buffer_ptr = buffer; // A const pointer to non-const data // We need to const_cast to pass it to process_string // because process_string expects a non-const char* process_string(const_cast(const_buffer_ptr)); std::cout << "After processing (Case 1): " << buffer << std::endl; // Case 2: Attempting to modify a truly const string (Undefined Behavior) const char* truly_const_string = "immutable"; // This data is in read-only memory process_string(const_cast(truly_const_string)); std::cout << "After processing (Case 2): " << truly_const_string << std::endl; // Using const_cast here to call process_string, but modifying *truly_const_string // results in undefined behavior because the underlying object is truly const. // This is generally discouraged and can lead to crashes or unexpected results. // For demonstration purposes only: // process_string(const_cast(truly_const_string)); // std::cout << "After processing (Case 2 - UB): " << truly_const_string << std::endl; return 0; }