C typedef with struct tag reuse: Will the following declaration compile and work as intended, creating both a struct tag and a typedef of the same name?\n\ntypedef struct s\n{\n int a;\n float b;\n} s;

Difficulty: Easy

Correct Answer: Yes; the struct tag namespace is distinct from the typedef namespace, so this is valid.

Explanation:


Introduction / Context:
C maintains separate namespaces for struct/union/enum tags and for ordinary identifiers (including typedef names). This question clarifies whether a struct tag and a typedef may share the same spelling.


Given Data / Assumptions:

  • Declaration uses both a struct tag `s` and a typedef name `s` in the same statement.


Concept / Approach:
The code declares a tag named `s` and simultaneously introduces a typedef name `s` that aliases `struct s`. Because tags and typedef names are in different namespaces, this is valid and common in C. Afterward, you can write `s var;` instead of `struct s var;`.


Step-by-Step Solution:
1) Parse the declaration: it defines `struct s { ... };`. 2) The trailing `} s;` introduces a typedef name `s` that refers to `struct s`. 3) The two uses of `s` live in different namespaces and do not conflict. 4) Using `s x;` now refers to the typedef type.


Verification / Alternative check:
Most codebases and textbooks demonstrate this idiom; it compiles cleanly on conforming C compilers.


Why Other Options Are Wrong:
Option B: Misinterprets namespaces; no redefinition here.
Option C: Works in both C and C++.
Option D/E: Member order or machine word size is irrelevant.


Common Pitfalls:
Confusing tag and typedef namespaces; thinking the second `s` shadows the first; assuming an ODR-like rule applies in C.


Final Answer:
Yes—valid and idiomatic; tag and typedef live in different namespaces.

Discussion & Comments

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