sizeof() 应用于结构体和变量
考虑以下代码片段:
struct foo {
int a;
int b;
int c;
};
struct foo f;
printf("%u, %u\n", sizeof(struct foo), sizeof(f));
代码返回相同的值,但我想知道应用于变量的 sizeof() 是否正确,或者这只是巧合?
谢谢。
consider the following snippet:
struct foo {
int a;
int b;
int c;
};
struct foo f;
printf("%u, %u\n", sizeof(struct foo), sizeof(f));
The code returns the same values, but I was wondering if sizeof() applied to variable is correct or this is just coincidence?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
两者都将并且确实应该返回相同的值。
来自 MSDN:
运算符的大小
sizeof 运算符给出存储操作数类型的对象所需的存储量(以字节为单位)。该运算符允许您避免在程序中指定与机器相关的数据大小。
Both will and should indeed return the same value.
From MSDN:
The sizeof Operator
The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.
sizeof
适用于类型 和表达式。当您将其应用于类型时,()
是sizeof
语法的一部分:sizeof(type)
。当您将其应用于表达式时,()
不是sizeof
语法的一部分:sizeof expression
。因此,您的第二个
sizeof
并不是真正“应用于变量”。它应用于表达式(f)
。该表达式由一个包含在一对冗余的()
中的单个变量f
组成。您也可以不使用冗余的()
对,而仅使用sizeof f
。当
sizeof
应用于表达式时,它返回表达式结果的大小(即表达式所具有的类型的大小)。在您的示例中,sizeof
的两个应用程序都保证计算出相同的值。事实上,一个好的编程习惯是尽可能避免使用
sizeof(type)
,即更喜欢使用sizeof表达式
。这使您的代码更加独立于类型,这总是一件好事。类型名称属于声明而不是其他地方。sizeof
works with types and expressions. When you apply it to a type, the()
are part ofsizeof
syntax:sizeof(type)
. When you apply it to an expression()
are not part ofsizeof
syntax:sizeof expression
.So your second
sizeof
is not really "applied to a variable". It is applied to an expression(f)
. That expression consists of a single variablef
enclosed into a redundant pair of()
. You could also do without that redundant pair of()
and use justsizeof f
.When
sizeof
is applied to an expression, it returns the size of the expression result (i.e. the size of the type that expression has). In your example both applications ofsizeof
are guaranteed to evaluate to the same value.In fact, a good programming practice is to avoid
sizeof(type)
as much as possible, i.e. prefer to usesizeof expression
. This makes your code more type-independent, which is always a good thing. Type names belong in declarations and nowhere else.这正如预期的那样,即两者将返回相同的值。该值是在编译时计算的。
在
sizeof
中使用变量通常是一个好习惯,因为您稍后可能会更改类型,因此大小也可能会更改。This is as expected, i.e. both will return the same value. This value is calculated at compile-time.
It's usually a good practice to use the variable in
sizeof
as you might later change the type and thus the size might change as well.一般来说,最好将其应用于变量。如果变量的类型发生变化,它将保持正确。
In general it is preferable to apply it to the variable. It will then remain correct if the type of the variable changes.