我有以下内容:
//h.h file
#pragma once
struct A { int x; };
//a.c file
#include "h.h"
struct A* a;
//b.c
#include "h.h"
extern struct A* const a;
int main() {}
我在 extern
声明中添加了额外的 const
。添加这个 const
会是 UB 吗?
如果不是 UB,那么在 main
中执行下面的操作就会是 UB 吗?
(*(struct A**)&a) = malloc(sizeof(struct A));
最佳答案
是的。来自附件 J.2:
- Two declarations of the same object or function specify types that are not compatible (6.2.7).
和 6.2.7 ¶2:
All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.
和 6.7.3 ¶10:
For two qualified types to be compatible, both shall have the identically qualified version of a compatible type; the order of type qualifiers within a list of specifiers or qualifiers does not affect the specified type.
关于c - extern 上的这个附加常量是 UB 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58205396/