C Coding Style – sizeof(type) vs sizeof(variable)

ccoding-style

I've seen two styles of using sizeof for memory-related operations (such as in memset or malloc):

  • sizeof(type), and
  • sizeof variable or sizeof(variable)

Which one would you prefer, or would you use a mix of the two styles, and when would you use each style? What are the pros and cons of each style and when you use them?

As an example, I can see the following pair of situations where one style helps and the other doesn't:

When you get the pointer indirection wrong:

type *var;
...
memset(var, 0, sizeof var);    /* oops */

When the type changes:

new_type var;    /* changed from old_type to new_type */
...
memset(&var, 0, sizeof(old_type));    /* oops */

Best Answer

I perfer sizeof(variable) over sizeof(type). Consider:

int a1;
float a2;
memset(&a1,0,sizeof(a1));
memset(&a2,0,sizeof(a2));

vs.

int a1;
float a2;
memset(&a1,0,sizeof(int));
memset(&a2,0,sizeof(float));

In the first case, it's easy to verify that the right sizes are being passed to memset. In the second case, you need to constantly review top and bottom sections to make sure you are consistent.

Related Topic