cboolean-operations

Why do I get this error? invalid operands to binary expression


I want to check if 2 struct pointers point to the same values, but I get this error:

./07ex.c:158:15: error: invalid operands to binary expression ('RGB' (aka 'struct RGB_') and 'RGB') return *x == *y; Here is the struct and the function:

typedef struct RGB_ {
    float r; 
    float g; 
    float b; 
} RGB;

bool point_to_equal_values_struct(RGB *x, RGB *y) {
    return *x == *y;
}

I got through this by doing it as such:

bool point_to_equal_values_struct(RGB *x, RGB *y) {
    if ((*x).r == (*y).r && (*x).g == (*y).g && (*x).b == (*y).b)
    {
        return true;
    }       
    return false;
}

But still, I am curious as to why the compiler gives out this error. Thanks in advance!


Solution

  • The == operator isn't defined to work on structs, so two structs can't be compared directly.

    You need to compare the corresponding fields as you did. On a side node, you probably want to use the -> operator to access members of a struct referenced by a pointer as it's easier to read:

    if (x->r == y->r && x->g == y->g && x->b == y->b)