- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我最近尝试了这段代码,但有点困惑。请参阅以下声明:
static st;
auto au;
register reg;
volatile vl;
const cn;
它们都在分配 4 字节的内存(在 32 位 GCC 上)。但是,当我尝试打印(使用 printf
函数)它们的尺寸时,它们无法正常工作并出现错误。
sizeof(const) // worked and printed 4
sizeof(volatile) // worked and printed 4
sizeof(auto) // error: expected expression before ‘auto’
sizeof(static) // error: expected expression before ‘static’
sizeof(register) // error: expected expression before ‘register’
我怀疑auto, static, register
keywords 也分配了 4 字节的内存(在 32 位架构上)。
但为什么这些会给出与 const
和 volatile
不同的错误?
最佳答案
在 1999 标准之前的 C 语言中,在许多情况下,未指定的类型将默认为 int
。
C99 放弃了该规则,现在省略类型是非法的(严格来说,这是约束违规,需要诊断——这可能是非致命警告)。无论如何,省略 int
类型一直不是一个好主意。 (它可以追溯到 C 的前身语言 BCPL 和 B,它们在很大程度上是无类型的。)
static st;
auto au;
register reg;
volatile vl;
const cn;
这些声明在 C90 中都是合法的(并且所有变量都是 int
类型),但在 C99 中它们是无效的。
sizeof(const)
sizeof(volatile)
令我惊讶的是,这些在 C90 中实际上是合法的(但在 C99 中不是)。 const
或 volatile
本身是一个类型名称,分别相当于 const int
和 volatile int
。从语法上讲,const
和 volatile
是类型限定符。
sizeof(auto)
sizeof(static)
sizeof(register)
区别在于:
const int x = 42;
将 x
定义为 const int
类型的对象,同时:
static int x = 42;
将 x
定义为 int
类型的 static 对象(static
不是类型的一部分).
这些都是语法错误,因为auto
、static
和register
不是类型名称。这些关键字是存储类说明符。
这解释了为什么前两个 sizeof
表达式似乎有效,而其他的则无效。但这并不是特别有用,因为如果您指定类型 int
(您总是应该这样做),那么 sizeof(const)
恰好有效并不重要(在 C90 中,而不是在 C99 中)。
底线是您应该始终在任何声明中指定类型。虽然你可以合法地编写sizeof(const int)
,但它保证与sizeof(int)
相同,所以使用const<没有太大意义
在那个上下文中。
关于来自 'sizeof' 运算符的令人困惑的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19709923/
我是一名优秀的程序员,十分优秀!