#define my_sizeof(x) ((&x + 1) - &x)
&x
gives the address of the variable (lets say double x) declared in the program and incrementing it with 1 gives the address where the next variable of the type x can be stored (here addr_of(x) + 8
, for the size of a double is 8Byte).
The difference gives the result that how many variables of type of x
can be stored in that amount of memory which will obviously be 1 for the type x (for incrementing it with 1 and taking the difference is what we've done).
#define my_size(x) ((char *)(&x + 1) - (char *)&x)
typecasting it into char*
and taking the difference will tell us how many variables of type char
can be stored in the given memory space (the difference). Since each char
requires only 1 Byte of memory therefore (amount of memory)/1 will give the number of bytes between two successive memory locations of the type of variable passed on to the macro and hence the amount of memory that the variable of type x
requires.
But you won't be able to pass any literal to this macro and know their size.