Is there a structural type equivalence in C?
Asked
Active
Viewed 3,263 times
3 Answers
3
Strictly, no - differently named types are different types, even if the structure of the types is the same. (Of course, a typedef
just introduces an alternative name for an existing type; such types are the same type.)
However, in practice, there are a number of stunts you can pull and get away with. But strictly, they are cheating. Using void pointers is one way of subverting the system; another is not using prototype declarations of functions; variable length argument lists can be another.

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278
-
Not sure if I agree 100%. C compilation works one compile unit at a time and so the compiler cannot for example decide to add random padding bytes to structures. Consider also the question of C++ POD types... how can they be compatible with C structures if C structures aren't compatible even among themselves? – 6502 Jan 29 '11 at 12:08
0
If you're asking if it's possible to compare two struct
for equality the answer is no. There is only assignment and you can return a structure from a function.

6502
- 112,025
- 15
- 165
- 265
-
-
I saw Leffler response if this is what you mean, but thought that the question COULD have been asking something different and that's why my answer starts with "if". Please remember that english is not the first language for many of us here - including me. – 6502 Jan 29 '11 at 11:52
-2
There is no operator to compare two struct's in C, you can use memcmp instead:
if( memcmp( &structvar1, &structvar2, sizeof structvar1 ) )
puts("not equal");
else
puts("equal");

user411313
- 3,930
- 19
- 16
-
2-1: This is not going to be a good way... there could be padding bytes that memcmp would consider – 6502 Jan 29 '11 at 11:52
-
you don't know what you say: padding on the same struct is the same padding, therefore it's never a problem for memcmp because sizeof includes this (same) padding for both arguments – user411313 Jan 29 '11 at 13:02
-
3You cannot know if the padding bytes are going to be equal in content (e.g. if the structures have been allocated with `malloc` the initial content is arbitrary). Using `memcmp` will tell you two structs are different while indeed they've all members equal. – 6502 Jan 29 '11 at 13:27