" C"的sizeof与类型或变量 [英] "C" sizeof with a type or variable

查看:118
本文介绍了" C"的sizeof与类型或变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近看到有人称赞其使用的sizeof变种来代替的sizeof(类型)的其他用户。我一直以为这仅仅是一个风格的选择。是否有任何显著区别?作为一个例子,与f和FF线被认为比使用g和gg的行更好

Recently saw someone commending another user on their use of sizeof var instead of sizeof(type). I always thought that was just a style choice. Is there any significant difference? As an example, the lines with f and ff were considered better than the lines with g and gg:

 typedef struct _foo {} foo;

 foo *f = malloc(count * sizeof f);
 foo *g = malloc(sizeof(foo) * count);

 foo **ff = malloc(count * sizeof *ff);
 foo **gg = malloc(sizeof(foo*) * count);

在我看来,第一套仅仅是一个风格问题。但在第二对线,额外的第二个*很容易混淆的乘法。

In my opinion, the first set is just a matter of style. But in the second pair of lines, the extra second * can easily be confused for a multiplication.

推荐答案

如果变量的类型改变时,sizeof的都不需要改变,如果变量是参数,而不是类型。

If the type of the variable is changed, the sizeof will not require changing if the variable is the argument, rather than the type.

关于@冰层的评论:可能性或变型与变量名的可能性不是问题。想象一下,变量名作为参数为sizeof再后来改变了。在最好的情况下,重构,重命名操作改变了这一切的发生和引入任何错误。在最坏的情况下,sizeof的实例错过和编译器会抱怨你解决它。如果类型更改完成后,没有错误的可能性在sizeof的语句。

Regarding @icepack's comment: the possibility or likelihood of change for type vs. variable name is not the issue. Imagine the variable name is used as the the argument to sizeof and then later changed. In the best case a refactor-rename operation changes all occurrences and no error is introduced. In the worst case an instance of a sizeof is missed and the compiler complains and you fix it. If the type is changed you are done, no possibility of errors at sizeof statements.

现在想象类型为sizeof的说法。如果变量的类型被改变时,还有比检查其他找到所有的sizeof涉及该​​变量没有手段。您可以搜索,但你会得到命中为同类型的sizeof的所有无关的用途。如果一个人错过了,你将有一个运行问题,由于大小不匹配,这是更为麻烦找。

Now imagine the type is the argument to sizeof. If the type of the variable is changed, there is no means other than inspection to find all sizeof relating to that variable. You can search, but you will get hits for all the unrelated uses of sizeof of the same type. If one is missed, you will have a runtime problem due to a size mismatch, which is much more trouble to find.

这篇关于" C"的sizeof与类型或变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆