4

Possible Duplicate:
How does the following code work?

#define TYPE_CHECK(T, S)                                       \
  while (false) {                                              \
    *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);      \
  }

I found it tricky, how does it work? And why volatile?

Community
  • 1
  • 1
tomsheep
  • 253
  • 1
  • 3
  • 7

4 Answers4

4

Since it's a static cast, it's getting the compiler to ensure that the pointers to the two types are equivalent. The while(false) ensures it's never run and that it's only a compile time thing.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
1

It statically checks that a S* can be cast into a T*. No code is executed at runtime. I think the volatile prevents optimization, which would just make the compiler ignore the code.

slaphappy
  • 6,894
  • 3
  • 34
  • 59
  • Optimization would not permit the compiler to ignore the code entirely, since the compiler still has to diagnose invalid code whether it's optimized away or not. I suspect the `volatile` is there to suppress a warning from some compiler that notices a null pointer is dereferenced. Well, it isn't since the expression isn't evaluated, but the expression says to do it. If I'm right, then `volatile` indicates "user appears to think he knows what he's doing, and really wants to dereference that null pointer, so don't warn". – Steve Jessop Aug 08 '11 at 10:23
0

The code is checking if S* can be assigned to T*, and forcing a compile error if it cannot. As for volatile I'm not sure.

john
  • 85,011
  • 4
  • 57
  • 81
-1

If the types can't be casted, it won't compile. But it is never executed.

Victor
  • 348
  • 2
  • 12