C structures: is this self-referential member declaration valid or an error?\n\nstruct emp\n{\n int ecode;\n struct emp e;\n};\n

Difficulty: Easy

Correct Answer: Error: in structure declaration

Explanation:


Introduction / Context:
This evaluates knowledge of self-referential structures. C allows a structure to have a pointer to itself but not an instance of itself as a member, because that would require infinite size.


Given Data / Assumptions:

  • struct emp contains int ecode and a member struct emp e (not a pointer).


Concept / Approach:
A structure’s size must be finite. If a structure contains a member that is an instance of the same type, computing the complete size becomes impossible (it would contain another full struct emp, which itself contains another full struct emp, ad infinitum). The valid idiom is to use a pointer: struct emp* e;.


Step-by-Step Solution:

Observe that the member e is a full struct emp, not a pointer.This creates a recursive type with no base case, making size computation impossible.Therefore the declaration is invalid and results in a compilation error.


Verification / Alternative check:
Replace struct emp e; with struct emp *e; and the declaration becomes valid. This pattern is widely used to build linked lists and trees.


Why Other Options Are Wrong:

  • Linker error: The issue is at compile-time, not link-time.
  • No error / None of the above: Contradicted by the reasoning above.


Common Pitfalls:
Assuming that since pointers are allowed, full nested instances are also allowed. Only pointers are permitted for self-reference inside the same structure.


Final Answer:
Error: in structure declaration

More Questions from Structures, Unions, Enums

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion