Cause compilation error in C89 if two types are not the same

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;

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.


T1 t1;
T2 *t2 = &t1;

This is a constraint violation if T1 and T2 are not the same.

Or,

T1 f();
T2 f() {}
链接地址: http://www.djcxy.com/p/73560.html

上一篇: 为什么双重否定力值成为布尔?

下一篇: 如果两种类型不相同,则会导致C89中的编译错误