c - extern 上的这个附加常量是 UB 吗?

标签 c constants language-lawyer undefined-behavior extern

我有以下内容:

//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/

相关文章:

C++线程堆栈地址范围

c - 如何将宏函数作为参数传递

javascript - 常量值作为数组元素给出错误

iOS:Swift 常量文件

c++ - const变量和const类型变量的区别

c++ - 位字段和值初始化导致缓冲区溢出 - 编译器错误或未定义的行为?

c - `(i) = 1` 在标准 C 中是非法的吗?

c++ - 在 "a"(追加)模式下打开文件时 fseek 不起作用

c - 无用条件下的变量修改

c - 如何使用指针将字符串分割成两个字符串? C语言