Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

gcc - Compatible types and structures in C

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;   /* Doesn't work */
    p = &a;  /* Doesn't work */

    return 0;
}

which fails to compile under GCC (3.4.6), with the following error:

test.c:8: error: incompatible types in assignment
test.c:9: warning: assignment from incompatible pointer type

Now, from what I understand (admittedly from the C99 standard), is that a and c should be compatible types, as they fulfill all the criteria in section 6.2.7, paragraph 1. I've tried compiling with std=c99, to no avail.

Presumably my interpretation of the standard is wrong?

Addendum

Incidentally, this question arises because I wanted to declare some template-like macros to wrap various datatypes without the overhead of having to declare named types/typedefs everywhere, e.g. a trivial example:

#define LINKED_LIST(T)   
    struct {             
        T    *pHead;     
        T    *pTail;     
    }

...

LINKED_LIST(foo) list1;
LINKED_LIST(foo) list2;

...

LINKED_LIST(foo) *pList = &list1;  /* Doesn't work */
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...