I've seen two styles of using sizeof
for memory-related operations (such as in memset
or malloc
):
sizeof(type)
, andsizeof variable
orsizeof(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)
oversizeof(type)
. Consider:vs.
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.