Question

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 ?

Était-ce utile?

La solution 2

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.

Autres conseils

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?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top