Alex Rivera | Logout

sizeof with a type or variable

Asked 2008-12-17T00:13:34.183
32

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.

Edit
Report

2 Answers

2

I tend to use sizeof(type) in memory allocation, but invariably sizeof(variable) when using a local or global variable. Nevertheless, there is wisdom in the advice to use the variable name all the time.

I also had a long discussion (rather animated at times, and it lasted over a period of days -- we ended agreeing to differ on the issue) about whether it is OK to use sizeof(variable) or whether it must be sizeof variable; that is, does it matter whether parentheses enclose the argument to sizeof. I've never encountered a compiler that witters about sizeof(variable), so I opt for uniformity and always use the parentheses with sizeof. My colleague was equally adamant that parentheses must not be used with variables; that somehow there is/was a valuable distinction between the notation with and without the parentheses. I've not been persuaded - I don't expect to be persuaded.

On a wholly different tack, a couple of other points about sizeof:

  • If you're using C99 and VLA - variable-length arrays - then sizeof(vla) is not a compile-time constant. Beware!
  • The C pre-processor does not understand sizeof which is a nuisance but logical.
answered 2008-12-19T07:17:27.883
0

Taking the sizeof a variable can have unexpected results. When the variable is an array, sizeof(array) will return the size of the array, not the size of an individual element or the size of a pointer. Taking the size of a pointer will return the size of a pointer. But since arrays are usually represented as pointers when being passed around, things can get confusing.

answered 2008-12-17T03:37:24.007

Your Answer