sizeof with a type or variable

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.


In addition to what Steve says, let me add that sizeof does not evaluate its operand. So you are free to do anything in it. Not only you can use not-yet initialized variables, but you can dereference a null-pointer, call functions not defined but only declared and do any other kind of stuff. I encourage you to always use the expression version for reasons Steve explained greatly.

Also consider that sometimes typenames are really long and unreadable, just think of pointers to functions (especially in C++). Instead of writing sizeof(my_long_type<weird, stuff>) you just do sizeof t.