Compatible types and structures in C

后端 未结 5 1066
深忆病人
深忆病人 2020-12-14 02:18

I have the following code:

int main(void)
{
    struct { int x; } a, b;
    struct { int x; } c;
    struct { int x; } *p;

    b = a;   /* OK */
    c = a;          


        
5条回答
  •  粉色の甜心
    2020-12-14 03:08

    struct { int x; } is a anonymous structure tag, two anonymous structures cannot have "the same name", which is a necessary condition for type compatibility. You can declare types that are compatible with a non-anonymous structure using typedef.

    struct tmp { int x; }; // declare structure tag
    typedef struct tmp type1;
    typedef struct tmp type2; // declare 3 types compatible with struct tmp
    typedef struct tmp type3; // and with each other
    
    type1 a, b;
    type2 c;
    type3 *p;
    b = a;
    c = a;
    p = &a;
    

提交回复
热议问题