C Tips: sizeof

This tip is so small it's embarrassing to share but I personally enjoy learning about tiny quirks like this.

There are two distinct applications of the `sizeof` operator:

  sizeof <value>
  sizeof(<type>)

Since the syntax for the latter case is equivalent to the former with extra parenthesis, it's common to always use the latter syntax in code.

I'm certain this is also how the common C beginner misconception that `sizeof` is a function and not an operator is perpetuated.

It's a tiny thing but I avoid the interchangeable syntax. It makes some edge cases less brittle and keeps me cognizant of what I'm sizing.

  struct foo *f = malloc(sizeof(struct foo)); /* not great */
  struct foo *f = malloc(sizeof(*f));         /* better */
  struct foo *f = malloc(sizeof *f);          /* preferable */

Since parenthesis are required when `sizeof` is applied to a type we know immediately the final example must refer to data we are using and if we change the type in the LHS of the statement the RHS is still correct.

Or put as a rule:

get your sizes from your data not your types

Devlog Index