C programming — spot the error related to forward declarations and prototypes.
#include
#include
void modify(struct emp*); /* prototype uses struct emp before its declaration /
struct emp
{
char name[20];
int age;
};
int main()
{
struct emp e = {"Sanjay", 35};
modify(&e);
printf("%s %d", e.name, e.age);
return 0;
}
void modify(struct emp p)
{
p->age = p->age + 2;
}
What is the correct assessment for standard C?
-
AError: in structure definition
-
BError: in prototype declaration unknown struct emp
-
CNo error
-
DLinker error only on some systems
Answer
Correct Answer: Error: in prototype declaration unknown struct emp
Explanation
Introduction / Context:This question examines how C handles tags (struct names) with respect to declarations and prototypes. Using a structure tag in a function prototype before the tag is declared requires at least a forward declaration of the tag.
Given Data / Assumptions:
- The function prototype void modify(struct emp); appears before struct emp is declared.
- No forward declaration (struct emp;) precedes the prototype.
Concept / Approach:In C, identifiers must be declared before use. A struct tag introduces a distinct namespace. To mention struct emp in a prototype prior to the full definition, you must forward declare it: struct emp; After that, the prototype may use struct emp safely, and the full definition can follow.
Step-by-Step Solution:
1) The prototype references struct emp before the compiler has seen any declaration of that tag.2) Without a prior tag declaration, the compiler reports that struct emp is unknown at the prototype.3) Fix: add a forward declaration line struct emp; above the prototype, or move the full struct definition above the prototype.Verification / Alternative check:Adding struct emp; makes the code compile; modify then increments age by 2 and the program prints "Sanjay 37".
Why Other Options Are Wrong:
- Structure definition error: The definition itself is fine.
- No error: Violates declaration-before-use for the tag in standard C.
- Linker error: The issue is purely compile-time, not linking.
Common Pitfalls:Assuming prototypes can reference undeclared tags; forgetting that struct tags form their own namespace and need forward declarations when used early.
Final Answer:Error: in prototype declaration unknown struct emp