pic11
pic11

Reputation: 14943

cast long into pointer

Can this cast fail and when?

long x=-1;
long y = (long)(void*)x;
assert(x==y);

More specifically, how to detect if the above cast is OK at compile time.

Upvotes: 4

Views: 3058

Answers (4)

harald
harald

Reputation: 6126

This may fail on architectures where a long int and a pointer is not the same size. Some 64bit architectures has this behaviour. Like Basile says, use intptr_t instead if available on your system.

You can detect this situation at compile time like this:

#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(COND)?1:-1]
STATIC_ASSERT((sizeof(void*) > sizeof(long)), incompatible_pointer_size);

Upvotes: 0

Patrick Schlüter
Patrick Schlüter

Reputation: 11841

Portably no. I know even an implementation where this will fail. x86 real mode with memory models tiny, small and medium. A long is 32 bit and pointers are 16 bits. Other microcontrollers with Harvard architecture will probably fail too.

Upvotes: 2

Kasper van den Berg
Kasper van den Berg

Reputation: 9526

As far as I remember this won't fail, given that you correct the type of y to (long)(void*).

Upvotes: 0

A more portable way (on the C99 standard variant) is to #include <stdint.h> and then cast pointers to intptr_t (and back). This integer type is guaranteed to be the size of a pointer.

Upvotes: 7

Related Questions