Implementation of sizeof operator

The result of pointer subtraction is in elements and not in bytes. Thus the first expression evaluates to 1 by definition.

This aside, you really ought to use parentheses in macros:

#define my_sizeof(x) ((&x + 1) - &x)
#define my_sizeof(x) ((char *)(&x + 1) - (char *)&x)

Otherwise attempting to use my_sizeof() in an expression can lead to errors.

Leave a Comment