Can I take an intptr_t
and assign or memcpy it to a uintptr_t
and back again and be guaranteed to end up with the same value?
That is, are either of the following guaranteed to work (no assert):
Using assignment:
intptr_t i1 = f();
uintptr_t u = i1;
intptr_t i2 = u;
assert(i1 == i2);
Using memcpy
:
intptr_t i1 = f();
uintptr_t u;
memcpy(&u, &i1, sizeof(u));
memcpy(&i2, &u, sizeof(u));
assert(i1 == i2);
If it is not guaranteed by the standard, it is possible to check a condition at compile or runtime to determine whether it is guaranteed on a particular platform.
The memcpy
is guarenteed to work, as it treats the values as a sequence of bytes. The assignment is not guarenteed to work, though will generally work on any machine that uses 2s complement integers. A machine that uses 1s complement or sign-magnitude will change the value of -0 to 0, though the assert will still be ok, since -0 == 0 is true.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.