0
C - Why can't you compare two structs?
It fails at == #include <stdio.h> int main() { typedef struct {char ch;} st; st s1 = {'c'}; st s2 = s1; if(s1 == s2) printf("successful"); return 0; }
4 odpowiedzi
+ 5
I believe the addresses are different.
So the test written would fail.
+ 4
You can't compare structs because the language doesn't know how to. Structs are objects you build yourself, which can become pretty complex, especially when pointers are involved, meaning a lot of choices are involved when attempting to generalize such an operation, which the language doesn't want to do, I guess. The only reason you can compare class instances in C++ in the first place is due to operator overloading, a concept that does not exist in C. For some additional reasons, see:
https://www.quora.com/Why-cant-I-directly-compare-two-structure-types-variables-in-C
https://stackoverflow.com/questions/7179174/why-doesnt-c-provide-struct-comparison
https://stackoverflow.com/questions/5740310/no-operator-found-while-comparing-structs-in-c
+ 2
The if statement should be like this
if(s1.ch == s2.ch)
Since there can be one or more members inside structure, so you need to identify that which member of the structure you want to compare.
+ 2
here is what I found as a possible solution to your query but not as to why you can't but possibly as to how you can:
https://stackoverflow.com/a/41548096/7218253