c - Swapping 2 function pointers without a temporary variable -
swapping 2 void pointers easy without using memory:
void* p1; void* p2; //... p1 = ((uintptr_t)p1) ^ ((uintptr_t)p2); p2 = ((uintptr_t)p1) ^ ((uintptr_t)p2); p1 = ((uintptr_t)p1) ^ ((uintptr_t)p2);
but swap function pointers must use pointer? (as not guaranteed fit integer type).
void (*p1)(); void (*p2)(); //... void (*tmp)() = p1; p1 = p2; p2 = tmp;
can give me example of portable method swap function pointers without using temporary variable?
i think works, because aliasing through (unsigned) char allowed:
void (*p1)(); void (*p2)(); (size_t = 0; < sizeof(p1); ++i) { ((unsigned char *)&p1)[i] ^= ((unsigned char *)&p2)[i] } (size_t = 0; < sizeof(p2); ++i) { ((unsigned char *)&p2)[i] ^= ((unsigned char *)&p1)[i] } (size_t = 0; < sizeof(p1); ++i) { ((unsigned char *)&p1)[i] ^= ((unsigned char *)&p2)[i] }
Comments
Post a Comment