C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Point Out Errors (Q.No. 9)
9.
Point out the error in the program?
#include<stdio.h>

int main()
{
    struct emp
    {
        char n[20];
        int age;
    };
    struct emp e1 = {"Dravid", 23};
    struct emp e2 = e1;
    if(e1 == e2)
        printf("The structure are equal");
    return 0;
}
Prints: The structure are equal
Error: Structure cannot be compared using '=='
No output
None of above
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
17 comments Page 2 of 2.

Mumtaz said:   1 decade ago
No, you cannot!
The only way to compare two structures is to write your own function that compares the structures field by field. Also, the comparison should be only on fields that contain data (You would not want to compare the next fields of each structure!).

Neelkant said:   1 decade ago
Answer is just simple because the operator "==" is defined only to operate with the int, float and char, But not with strings, structure, unions or enums in C. In C++ it can be solved using operator overloading concept.

Sanju said:   1 decade ago
It possible to compare only when there must be pointer variable else error.

Alfaz said:   1 decade ago
Why we are not using '==' to compare the structure is if any of the structure contains union, floating point variables, pointers etc. Structure that does not contain this variables then we can directly go for field by field comparison or using

memset (&myStruct, 0, sizeof(myStruct));

This will set the whole structure (including the padding) to all-bits-zero. We can then do a memcmp() on two such structures.

memcmp (&s1,&s2,sizeof(s1));

Wozniak said:   1 decade ago
We should not compare structures because of the holes between the member fields of a structure.

Robert said:   9 years ago
Comparing the structures themselves as variables won`t work.

You have to do:
#include

int main()
{
struct emp
{
char n[20];
int age;
};
struct emp e1 = {"Dravid", 23};
struct emp e2 = e1;
if(e1.n == e2.n, e1.age == e2.age)
printf("The structure are equal");
return 0;
}

Compare each element of the structure.

Shalivahana nandish said:   9 years ago
You should not compare structure variables directly,using *pointer variables comparing two varables is possible .ex is given below.

#include <stdio.h>
int main()
{
struct emp
{
char n[20];
int age;
};
struct emp *e1 = {"Dravid", 23};
struct emp *e2 = e1;
if(e1<=e2)
printf("The structure are equal");
return 0;
}
op:The structures are equal.


Post your comments here:

Your comments will be displayed after verification.