-2

In c(not c++), is there a way to check in compile time the identity of the definitions of two structures with different tags? Do they consist of the same set of fields in the same order?

arkayu
  • 5
  • 2
    I wonder if this is an X-Y problem. In a comment you say "In the standard, two structures defined separately are formally incompatible, even if they have identical sets of fields." That's only true if the two structure types are defined separately *in the same translation unit*. Two structure types defined in two different translation units are compatible if they have the same tag and the same fields in the same order with the same names. – rici Sep 08 '21 at 04:50
  • `struct_this* a; struct_that* b; a = b;` If the structs are compatible, the assignment is possible. Otherwise, you get a compiler diagnostic message. – Lundin Sep 08 '21 at 06:56
  • 1
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 13 '21 at 22:10

1 Answers1

0

To my knowledge, it is not possible in C to iterate over struct members, which is what you'd probably have to do. Best you can do is check if two variables/types have the same size using sizeof or if two variables are of the same type.

Ætérnal
  • 332
  • 2
  • 4
  • Thanks for the answer. In the standard, two structures defined separately are formally incompatible, even if they have identical sets of fields. I hope that I missed some other way of checking or some trick, perhaps in the latest language editions. Checking with sizeof will only detect a gross mismatch. In my case, this does not solve the problem. – arkayu Sep 08 '21 at 03:27
  • @arkayu So, what is your (real) problem? – the busybee Sep 08 '21 at 05:30
  • There is a task to add the same subgroup of fields to different structures. The structures are defined independently in different header files, and there is a possibility of an error. The idea was to define an additional structure from a subgroup of fields in each case and check in compile time their identity. Another option is to define a structure from a subgroup of fields in one place and use it when defining structures containing this set of fields. But in this case, it will no longer be a set of fields, but a single field, a structure containing this set. – arkayu Sep 08 '21 at 10:35
  • 1
    @arkayu, if you have two definitons of the same `struct` (with the same tag name) in the same compilation unit (at the same scope) the compiler will throw an error about a single type (same tag) with two different definitions. – Luis Colorado Sep 10 '21 at 12:42