Partial structure initialization in C: unnamed members default to zero. What does this print?
#include
int main()
{
struct emp
{
char name[20];
int age;
float sal;
};
struct emp e = {"Tiger"}; // only name given; others default-initialized
printf("%d, %f
", e.age, e.sal);
return 0;
}
-
A0, 0.000000
-
BGarbage values
-
CError
-
DNone of above
-
ECompiler dependent
Answer
Correct Answer: 0, 0.000000
Explanation
Introduction / Context:Structures in C can be partially initialized with aggregate initializers. Understanding what happens to unspecified members avoids undefined behavior and misinterpretation of output.
Given Data / Assumptions:
- A struct has three members: char name[20]; int age; float sal;
- Initializer provides only the first member: {"Tiger"}.
- Printing the numeric members age and sal.
Concept / Approach:In an aggregate initializer, any members not explicitly initialized are initialized as if by zero. This rule applies regardless of storage duration when an initializer is present. Therefore, age becomes 0 and sal becomes 0.0.
Step-by-Step Solution:Assign name = "Tiger".Omitted members age and sal → set to 0 and 0.0 respectively.Print “0, 0.000000”.
Verification / Alternative check:Explicitly writing struct emp e = {"Tiger", 0, 0.0f}; yields identical behavior; both are well-defined.
Why Other Options Are Wrong:B: Not garbage—there is an initializer. C: No syntax error. D/E: The behavior is specified by the C standard and is not implementation dependent in this context.
Common Pitfalls:Confusing uninitialized automatic structs (indeterminate) with partially initialized ones (rest zero). Forgetting the difference between designated and positional initializers.
Final Answer:0, 0.000000