gpt4 book ai didi

来自 'sizeof' 运算符的令人困惑的结果

转载 作者:太空狗 更新时间:2023-10-29 17:04:41 26 4
gpt4 key购买 nike

我最近尝试了这段代码,但有点困惑。请参阅以下声明:

 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 位架构上)。

但为什么这些会给出与 constvolatile 不同的错误?

最佳答案

在 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 中不是)。 constvolatile 本身是一个类型名称,分别相当于 const intvolatile int。从语法上讲,constvolatile类型限定符

sizeof(auto)
sizeof(static)
sizeof(register)

区别在于:

const int x = 42;

x 定义为 const int 类型的对象,同时:

static int x = 42;

x 定义为 int 类型的 static 对象(static 不是类型的一部分).

这些都是语法错误,因为autostaticregister 不是类型名称。这些关键字是存储类说明符

这解释了为什么前两个 sizeof 表达式似乎有效,而其他的则无效。但这并不是特别有用,因为如果您指定类型 int(您总是应该这样做),那么 sizeof(const) 恰好有效并不重要(在 C90 中,而不是在 C99 中)。

底线是您应该始终在任何声明中指定类型。虽然你可以合法地编写sizeof(const int),但它保证与sizeof(int)相同,所以使用const<没有太大意义 在那个上下文中。

关于来自 'sizeof' 运算符的令人困惑的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19709923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com