#include<stdio.h>
#define MYSIZEOF(X) ((X*)0 +1)
int main()
{
printf("%ld", MYSIZEOF(int));
return 0;
}
Can any one please explain how it works ? thanks in advance
#include<stdio.h>
#define MYSIZEOF(X) ((X*)0 +1)
int main()
{
printf("%ld", MYSIZEOF(int));
return 0;
}
Can any one please explain how it works ? thanks in advance
The idea here is simple: arithmetic on a pointer to a type T
is performed in multiples of the sizeof(T)
, so ((X*)0 +1)
will - hopefully - be a pointer to an address sizeof(X)
bytes into memory.
Unfortunately, the behaviour's undefined as (X*)0
creates a NULL pointer, and the compiler may substitute some non-zero value used as that sentinel on the system it's compiling for. Further, the code assumes %ld
is the right format for a pointer, and it may not be. %p
would be an improvement if the printf
implementation supports it.
Of course, it's silly not to use the sizeof
operator directly....