pointer cast to (void *) then back to original type = unchanged?

K

Kobu

Does the C standard guarantee that a value of type (T*) casted to
(void*) then back to (T*) later on, will be equal to the original
value?
 
C

Chris Torek

Does the C standard guarantee that a value of type (T*) casted to
(void*) then back to (T*) later on, will be equal to the original
value?

Yes. More precisely, the result will *compare* equal to the
original value when using the "==" operator. This guarantee
does not cover the underlying representation, if pointers have
some "padding" bits for instance. Hence:

T *p1, *p2;
void *intermediate;

... set p1 to a valid value ...
intermediate = p1;
p2 = intermediate;
if (p1 != p2)
puts("ERROR, not equal in value");
if (memcmp(&p1, &p2, sizeof p1) != 0)
puts("equal value, but different representations");

is allowed to produce the second output line ("equal ... but
different").
 
I

infobahn

Kobu said:
Does the C standard guarantee that a value of type (T*) casted to
(void*) then back to (T*) later on, will be equal to the original
value?

No need to cast. If T is some object type, you can do this:

int foo(T *p)
{
void *v = p;
T *q = v;
return p == q; /* always returns 1 */
}

This guarantee does NOT extend to function pointers, and no, adding
a cast won't help.
 
K

Kevin Bracey

In message <[email protected]>
infobahn said:
No need to cast. If T is some object type, you can do this:

int foo(T *p)
{
void *v = p;
T *q = v;
return p == q; /* always returns 1 */
}

This guarantee does NOT extend to function pointers, and no, adding
a cast won't help.

But you can cast a function pointer to any different function pointer type
and back again, and get the same value back. Thus, say void (*)(void) would
serve as a type for generic function pointer. But unlike void *, you have to
cast each way.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,416
Latest member
LionelQ387

Latest Threads

Top