Difficulty: Medium
Correct Answer: A conforming C compiler should diagnose assigning the integer 5 to an int * without a cast as an error, so the program does not compile cleanly
Explanation:
Introduction / Context:
This question examines pointer initialization rules in C and what happens when you assign an arbitrary integer constant to a pointer. Understanding what is allowed and what should be rejected by the compiler is essential for writing safe, portable C code.
Given Data / Assumptions:
Concept / Approach:
In standard C, only the integer constant 0 has a special meaning when assigned to a pointer, producing the null pointer. Assigning any other integer value to a pointer without an explicit cast is not a usual, well defined operation and is at best highly non portable. Good compilers treat assignment of a nonzero integer constant to a pointer of unrelated type as a constraint violation and issue a diagnostic, often treating it as an error when warnings are elevated. Even if the code were forced to compile, printing a pointer with the integer format "%d" would be undefined behaviour.
Step-by-Step Solution:
Step 1: Look at int *p = 5;. This attempts to assign the integer 5 directly to a pointer to int.Step 2: According to the language rules, only 0 is guaranteed to convert to a valid null pointer without a cast. Other integer values require explicit casts and may still produce invalid addresses.Step 3: A conforming compiler is expected to diagnose this as an invalid initialization, at least with a warning. In many teaching contexts this is treated as a compilation error.Step 4: Because of this, the most appropriate description is that the program does not compile cleanly, rather than focusing on hypothetical runtime output.
Verification / Alternative check:
If you try to compile such code with warnings enabled, typical compilers emit messages like "incompatible integer to pointer conversion" for the line initializing p. If warnings are treated as errors, the build fails, which matches the chosen answer.
Why Other Options Are Wrong:
Option A assumes that 5 becomes both a valid pointer and a correctly printed integer, which is not guaranteed or portable.Option B discusses junk values or crashes, which may happen if the code is forced to compile, but this ignores the more fundamental compile time issue.Option C is incorrect because uninitialized pointers do not automatically become null; in this case the pointer is explicitly initialized with 5.
Common Pitfalls:
Programmers sometimes treat pointers and integers as freely interchangeable, which is dangerous and non portable. Only the conversion of 0 to a null pointer is defined and safe in this simple way. Printing pointers also requires the %p format and a cast to void *, not %d.
Final Answer:
The best description is A conforming C compiler should diagnose assigning the integer 5 to an int * without a cast as an error, so the program does not compile cleanly.
Discussion & Comments