我可以使用常量结构进行循环引用吗?
Am I allowed to make circular references with constants structs?
我可以在 C99 中执行此操作吗?
typedef struct dlNode {
dlNode* next, prev;
void* datum;
} dlNode;
const static dlNode head={
.next = &tail,
.prev = NULL,
.datum = NULL
};
const static dlNode tail={
.next = NULL,
.prev = &head,
.datum = NULL
};
没有这个我也可以让我的程序运行。就是方便。
可以。您只需转发声明 tail
即可使其正常工作:
typedef struct dlNode {
struct dlNode* next;
struct dlNode* prev;
void* datum;
} dlNode;
const static dlNode tail;
const static dlNode head={
.next = &tail,
.prev = NULL,
.datum = NULL
};
const static dlNode tail={
.next = NULL,
.prev = &head,
.datum = NULL
};
绝对允许这样做:添加tail
的前向声明,C会将其与后面的定义合并:
typedef struct dlNode {
const struct dlNode* next, *prev;
void* datum;
} dlNode;
const static dlNode tail; // <<== C treats this as a forward declaration
const static dlNode head={
.next=&tail,
.prev=NULL,
.datum=NULL
};
const static dlNode tail={ // This becomes the actual definition
.next=NULL,
.prev=&head,
.datum=NULL
};
请注意,您应该修改 struct
声明以使 next
和 prev
常量,否则您的定义将丢弃常量限定符。
我可以在 C99 中执行此操作吗?
typedef struct dlNode {
dlNode* next, prev;
void* datum;
} dlNode;
const static dlNode head={
.next = &tail,
.prev = NULL,
.datum = NULL
};
const static dlNode tail={
.next = NULL,
.prev = &head,
.datum = NULL
};
没有这个我也可以让我的程序运行。就是方便。
可以。您只需转发声明 tail
即可使其正常工作:
typedef struct dlNode {
struct dlNode* next;
struct dlNode* prev;
void* datum;
} dlNode;
const static dlNode tail;
const static dlNode head={
.next = &tail,
.prev = NULL,
.datum = NULL
};
const static dlNode tail={
.next = NULL,
.prev = &head,
.datum = NULL
};
绝对允许这样做:添加tail
的前向声明,C会将其与后面的定义合并:
typedef struct dlNode {
const struct dlNode* next, *prev;
void* datum;
} dlNode;
const static dlNode tail; // <<== C treats this as a forward declaration
const static dlNode head={
.next=&tail,
.prev=NULL,
.datum=NULL
};
const static dlNode tail={ // This becomes the actual definition
.next=NULL,
.prev=&head,
.datum=NULL
};
请注意,您应该修改 struct
声明以使 next
和 prev
常量,否则您的定义将丢弃常量限定符。