Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to check if a variable is of type struct?

Tags:

c

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?

like image 490
Fabricio Avatar asked Dec 12 '22 01:12

Fabricio


2 Answers

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.

like image 65
Ernest Friedman-Hill Avatar answered Dec 30 '22 23:12

Ernest Friedman-Hill


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);  
like image 33
ouah Avatar answered Dec 31 '22 00:12

ouah