Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
545 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...