C programming — determine whether these two structs can be compared with ==.\n\n#include<stdio.h>\n\nint main()\n{\n struct emp\n {\n char n[20];\n int age;\n };\n struct emp e1 = {"Dravid", 23};\n struct emp e2 = e1;\n\n if (e1 == e2)\n printf("The structures are equal");\n return 0;\n}\n\nWhat is the correct assessment?

Difficulty: Easy

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 '=='

More Questions from Structures, Unions, Enums

Discussion & Comments

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