const in the C language allows restricting the modifiability of an object. When working with function parameters, it helps protect data from accidental modification. The key difference in the declaration depends on what the const modifier relates to and where it is positioned relative to the pointer.
Example of different declarations:
void func(const int *ptr); // pointer to constant int void func(int * const ptr); // constant pointer to int void func(const int * const ptr); // constant pointer to constant int
const int *ptr — data is immutable, the pointer itself can be reassigned.int *const ptr — data is mutable, but the pointer cannot be reassigned.const int *const ptr — neither data nor pointer can be changed within the function.Proper use of const: allows:
void print_array(const int *arr, size_t n) { for (size_t i = 0; i < n; ++i) { printf("%d\n", arr[i]); // arr[i] = 10; // error: attempt to modify const data } }
Question: Can a regular pointer be assigned the address of a constant variable?
Expected wrong answer: "Yes, if you remove const from the pointer declaration, the compiler allows it."
Correct answer: "Lowering const" is only permissible with explicit type casting (casting), but this leads to undefined behavior when attempting to modify an object declared as const. This should not be done — it violates the const semantics and leads to runtime errors.
Example:
const int x = 5; int *ptr = (int*)&x; *ptr = 10; // UB: modifying const object
Story
In a large project, a programmer tried to bypass the const protection by casting a const pointer to a regular one and modifying data in the read-only memory segment. On some platforms, this resulted in a program crash (segmentation fault), and on others, it caused subtle bugs that were difficult to debug.
Story
In a library for array operations, a developer forgot to declare parameters as const. As a result, an incorrect function call accidentally modified the original data, leading to desynchronization of the array state and serious bugs in subsequent processing blocks.
Story
When writing a callback function passed to a third-party library, the const specification for the input buffer was forgotten. The library attempted to modify data in a constant string, leading to crashes on some operating systems and prolonged investigations into the source of the problem.