Using only the features of C89, given
typedef [unspecified token sequence] T1;
typedef [another unspecified token sequence] T2;
exhibit a language construct which will compile without error if and only if T1 and T2 are the same type (not just compatible). The limitation to C89 is because this is going into an autoconf probe.
EDIT: I need a solution which works even if T1 or T2 or both are incomplete types. Sorry for not mentioning this before.
SON OF EDIT: All three current answers only detect compatible types. This turns out to be much closer to "the same type" than I remembered, close enough for my current purposes, but out of curiosity I am still looking for an answer that detects the same type. Here are some pairs of types that are compatible but not the same:
typedef void (*T1)(void);
typedef void (*T2)();
typedef float T1[];
typedef float T2[12];
typedef enum { ONE, TWO, THREE } T1;
typedef /* implementation-defined integer type */ T2;
Answer
I think you should be able to utilize the strict type checking of extern
declarations:
typedef int T1;
typedef char T2;
extern T1 t1;
T2 t1;
The above will not compile. Changing T2 to an int
will allow the source to build correctly.
This will also not compile:
typedef int T1;
typedef unsigned int T2;
extern T1 t1;
T2 t1;
Even though both types are int
. Which I think is what you want.
However, this will not trigger an error:
typedef emum {Foo} T1;
typedef unsigned T2;
So it's not 100% waterproof. However, one has to keep in mind that there's nothing one can do with an enum
that can't also be done with an unsigned
. They have the same layout and can be used interchangeably. Effectively, they are the same type.
No comments:
Post a Comment