3 ms·
EDIT: the example below is valid, but it neither swaps the pointers, nor does it avoid extra registers/stack usage; and there is no way to use Unions to achieve
by tsimionescu 5y ago
EDIT: the example below is valid, but it neither swaps the pointers, nor does it avoid extra registers/stack usage; and there is no way to use Unions to achieve this, even in C, as calling `swapI(&(((union swappable*)x)->i), &(((union swappable*)y)->i))` is UB.
The best way to do this in C (NOT C++) would be with unions, assuming you know the size of int and float for your platform.
The following would be valid C:
union swappable{
float f;
int i;
}
void swapF(float* x, float* y) {
swappable xs, ys;
xs.f = *x;
ys.f = *y;
swapI(&xs.i, &ys.i);
}
Given that they are using overloaded functions though, we're in C++ land where there is no correct way to achieve it (or maybe you could with char*, as that is allowed to alias?).
- OskarS 5y agoThe best way to do this in C++ is using std::bit_cast, which unfortunately only became available in C++20. Before that, you have to memcpy. That works just fine, but the syntax is a bit clunky and it doesn’t work in constexpr contexts, which is why std::bit_cast was introduced. Compilers will optimize all of this to the same machine code.
- unnah 5y agoInteresting... I thought for sure that would be undefined behaviour like in C++, but apparently it has been defined since C99: https://en.cppreference.com/w/c/language/union https://en.cppreference.com/w/c/language/union
- sltkr 5y agoThat code doesn't even swap the floats.