Suppose I have the following structs:
struct A{
int a;
} a;
struct B{
A a;
int b;
} b;
how to check if b
is of type B
or if b
is of the type A
?
Do you mean at runtime, given a void *
that points to one or the other? Unfortunately, this is not possible; C doesn't have any kind of runtime type information mechanism.
At compile time:
#define WARN_IF_DIFFERENT_STRUCT_TYPE_1(T, o) do { \
T temp = (o); \
(void) temp; \
} while (0)
example:
struct B b;
/* will warn if b is not of struct A type */
WARN_IF_DIFFERENT_STRUCT_TYPE_1(struct A, b);
With two objects passed as macro parameters using typeof
GNU extension:
#define WARN_IF_DIFFERENT_STRUCT_TYPE_2(o1, o2) do { \
typeof(o1) temp = (o2); \
(void) temp; \
} while (0)
example:
struct A a;
struct B b;
/* will warn if a and b are not the same struct type */
WARN_IF_DIFFERENT_STRUCT_TYPE_2(a, b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With