1

Code 1:

struct demo
{
    int a;
}d[2];

int main()
{
    d[0].a=5;
    d[1]=d[0];
    return 0;
}

This code works fine

Code 2:

struct demo
{
    int a;
}d[2];

int main()
{ 
    d[0].a=5;
    d[1]=d[0];
    if(d[0]==d[1])
    {
        printf("hello");
    }
return 0;
}

This code gives error

error: invalid operands to binary == (have 'struct demo' and 'struct demo')

Why this error is coming in Code 2 ?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
kevin gomes
  • 1,775
  • 5
  • 22
  • 30
  • 1
    You can't compare arbitrary structs with `==`, write your own comparison function or use `memcmp`. – user2802841 Feb 11 '14 at 16:48
  • @Barmar why all this talk of `memcmp` in those answers? I don't get it, struct's can have padding which we can't know the value of. The other linked answer to, so weird. – Shafik Yaghmour Feb 11 '14 at 18:19

2 Answers2

6

C has no support for struct comparison. You have to compare the struct yourself by comparing all members one by one.

How do you compare structs for equality in C?

Community
  • 1
  • 1
Manuel Selva
  • 18,554
  • 22
  • 89
  • 134
5

You need to compare the members of the struct yourself, like this:

if(d[0].a ==d[1].a)

structs are not valid operands for equality(==), the operands have to be an arithmetic type or a pointer. We can see this from the draft C99 standard section 6.5.9 Equality operators:

One of the following shall hold:

  • both operands have arithmetic type
  • both operands are pointers to qualified or unqualified versions of compatible types;
  • one operand is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void; or
  • one operand is a pointer and the other is a null pointer constant.
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740