Introduction / Context:
Const-correctness ensures that objects declared read-only are not modified inadvertently. When a function takes an int *, passing it the address of a const int violates that promise. Even though some legacy compilers accept such code with only a warning, the intent of the language is to forbid discarding const implicitly. This question examines the compile-time consequence of attempting to modify a const array element through a non-const pointer parameter.
Given Data / Assumptions:
- const int arr[5] = {1,2,3,4,5};
- int fun(int *f) { *f = 10; return 0; }
- Call site: fun(&arr[3]); after printing arr[3].
Concept / Approach:
- The type of &arr[3] is const int *. Converting to int * would allow writing through the pointer to a const object, which is disallowed.
- Modern compilers issue an error; older ones might warn but still compile, leading to undefined behavior at runtime if a write occurs.
- Therefore, the correct, standard-conforming outcome is a type error at the call.
Step-by-Step Solution:
Identify parameter type mismatch: fun expects int * but receives const int *.Implicit cast would remove const → forbidden.Compiler issues a diagnostic; the program should not compile successfully.
Verification / Alternative check:
If you change fun to accept const int * and remove the write, the call compiles. If you remove const from arr, the original fun compiles and sets arr[3] to 10.
Why Other Options Are Wrong:
- ”Before…4 After…10”: implies the illegal write succeeded.
- ”Invalid parameter”: vague, not the standard type mismatch description.
- ”Before…4 After…4”: would require that the write be ignored; the core issue is a compile-time type error.
Common Pitfalls:
- Assuming that a warning is harmless; writing through a pointer to const invokes undefined behavior.
- Confusing array decays and pointer types; the const-qualification applies to the pointed-to object.
Final Answer:
Error: cannot convert parameter 1 from const int * to int *
Discussion & Comments