"C" sizeof with a type or variable

jmucchiello picture jmucchiello · Dec 17, 2008 · Viewed 17.1k times · Source

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.

Answer

Steve Fallows picture Steve Fallows · Dec 17, 2008

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.