0
#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

sunil
  • 61
  • 3
  • 2
    @ChrisBeck unrelated (that's finding the size of an array, where this code is finding the pointer to the PTE "iterator" of an implicit single-element array (which is valid in C++) but it tries to interprets the integral value of the resulting address...?) – sehe Sep 03 '15 at 06:52
  • 1
    @sehe yeah i realize that now, not actually any "sizeof" in there... time for sleep i think :X – Chris Beck Sep 03 '15 at 06:52
  • 3
    Why the down votes ? – Jabberwocky Sep 03 '15 at 06:55
  • 1
    @MichaelWalz People tend to dislike [tag:c]/[tag:c++] double-tagging, and the sight of ` (X*)0` is a sign that this is needlessly flirting with UB. Also "what does this code do" without an idea is basically "dear lazy-web", could trigger some people. There's not a lot to love about this question, honestly (I didn't downvote) – sehe Sep 03 '15 at 06:58
  • 1
    I don't think this is an appropriate duplicate. The duplicate only covers one small aspect related to this question – M.M Sep 03 '15 at 07:27

1 Answers1

6

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....

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • And then, the integral value of a pointer might not lend itself to direct interpretation. Instead it could be compared to the nullptr again. I don't think taking the integral value of a nullptr is UB per se (but interpreting it is IB) – sehe Sep 03 '15 at 07:00
  • 1
    @venki Yes. It's just adding numbers on your implementation. Google "pointer arithmetics" – sehe Sep 03 '15 at 07:00
  • 1
    @sehe: *" I don't think taking the integral value of a nullptr is UB per se"* - but adding to it might carry it across a segment boundary or something... I believe that is undefined (you can only reason about pointer arithmetic within specific arrays, up until the one-past-the-end address). – Tony Delroy Sep 03 '15 at 07:21