The problem is exactly what the compiler tells you, which does not know how to compare the two elements passed.
Consider a structure that represents a Cartesian point in a plane 2d:
typedef struct {
int x;
int y;
} Ponto;
If we now try to create colon and compare with ==
will not work:
int main(){
Ponto p1 = {10, 20};
Ponto p2 = {10, 20};
if (p1 == p2){
printf("iguais");
}
else {
printf("diferentes");
}
return 0;
}
Because the compiler does not know how to compare two points. In fact the error:
no match for 'operator ==' (operand types are 'Point' and 'Point')
It only happens if you are compiling in C ++, if you are compiling in C as it should the error is different, although it means the same:
invalid operands to binary == (have 'Point {aka struct}' and 'Point {aka struct}')
The way to solve in C is to compare the individual fields that represent equality for you. You can even do a function for this, or maybe use memcmp
to compare all memory, but not end will represent the same logic.
In my example comparing field to field would look like this:
if (p1.x == p2.x && p1.y == p2.y){
printf("iguais");
}
else {
printf("diferentes");
}
Comparing with memcmp
:
if (memcmp(&p1, &p2, sizeof(Ponto)) == 0){
printf("iguais");
}
else {
printf("diferentes");
}
In this last one, you need to not only pass the memory address of the two elements to compare, but also the number of bytes to compare in memory. The return is 0
when both memory blocks are equal, in the case when the two points are equal. It is also important to mention that you need header <string.h>
for memcmp
.
This type of comparison is less common because it uses all fields of the structure, which in many cases is not what is intended. And if any of the fields is a pointer the comparison checks whether the pointer is the same or if it points to the same place and not if the value is equal.
See these two examples on Ideone