C programming — determine whether these two structs can be compared with ==.
#include
int main()
{
struct emp
{
char n[20];
int age;
};
struct emp e1 = {"Dravid", 23};
struct emp e2 = e1;
if (e1 == e2)
printf("The structures are equal");
return 0;
}
What is the correct assessment?
-
APrints: The structures are equal
-
BError: Structure cannot be compared using '=='
-
CNo output (condition is unspecified)
-
DRuntime crash due to padding
Answer
Correct Answer: Error: Structure cannot be compared using '=='
Explanation
Introduction / Context:The question targets whether C permits comparing entire structures using the == operator. Copying one struct to another is allowed, but comparison is a different rule.
Given Data / Assumptions:
- Two struct emp variables e1 and e2 exist and contain identical field values.
- An if condition attempts e1 == e2.
Concept / Approach:Standard C allows assignment between compatible structure types (e2 = e1) but does not define == or != for entire structure operands. You must compare field-by-field, e.g., using strcmp for character arrays and direct comparison for integers.
Step-by-Step Solution:
1) Recognize e1 == e2 is a structure vs structure comparison.2) The C language does not define == for structs; attempting it is a compile-time error.3) Correct approach: compare e1.age == e2.age and strcmp(e1.n, e2.n) == 0.Verification / Alternative check:Compilers emit an error like “invalid operands to binary == (have struct emp and struct emp)”. Fieldwise comparison compiles and behaves as expected.
Why Other Options Are Wrong:
- Prints equal: Impossible; code does not compile.
- No output unspecified: The problem occurs at compile time, not runtime.
- Runtime crash due to padding: Padding is unrelated; the operator itself is illegal.
Common Pitfalls:Assuming struct comparison works like in C++ or in some compiler extensions. In portable C, compare members explicitly.
Final Answer:Error: Structure cannot be compared using '=='