Is there a way I can swap two values (a and b), which are of different data types (e.g. int and float) without using the built-in swap()
function in C++?
Asked
Active
Viewed 1,278 times
0
-
You might have some serious design issue. You use different types to represent different data. Even if different data uses same underlying data type you wouldn't want to swap (e. g. frequency and volume – pretty meaningless, wouldn't you agree?). Sometimes there are API incompatibilities (e. g. representing RGBA as four bytes or uint32_t, but some library expects four float values), but then you'd rather *convert* than swap. Seems to be an [XY problem](https://en.wikipedia.org/wiki/XY_problem) (or [XY problem](http://xyproblem.info/))... – Aconcagua Jul 09 '20 at 06:30
2 Answers
2
Well you can't do it with the built in swap
function, which takes two values of the same type. Of course you can just write some code to do the swap
int a = ...;
float b = ...;
// swap a and b
int save_a = a;
a = b;
b = save_a;
Wrap that up in a function if you need to.

john
- 85,011
- 4
- 57
- 81
-
is it actually correct to assign float to int? no precision loss occurs? – mangusta Jul 08 '20 at 06:02
-
1@mangusta You do lose precision when you assign a float to an int (any fractional part is dropped) whether that's correct or not depends on context. – john Jul 08 '20 at 06:03
-
3Wanting to swap a float and an int is a pretty strange requirement, but I'm not making judgements. – john Jul 08 '20 at 06:04
-
But you can't swap two values of different types as well, untill both are compatible with each other. In `int` and `float` case `float` can be narrowed to `int`. – foragerDev Jul 08 '20 at 06:57
-
@mangusta Actually, the issue is more complex. Assuming `float` and `int` are of same size and `float` follows IEEE 754, you can lose precision in **both** directions. On typical modern hardware, both types are of same size of 32 bits. `float`s are devided up into a sign bit, mantissa and exponent ([IEEE 754: 1:24:8](https://en.wikipedia.org/wiki/IEEE_754#Basic_and_interchange_formats) – yes, 33, bits: in normalised form, one mantissa bit is *implicit*), though, so if the int uses more than 24 bits, the surplus least significant bits are dropped as well. – Aconcagua Jul 09 '20 at 06:18
-
Additionally if the float value is not in the range of [`INT_MIN`, `INT_MAX`] **undefined behaviour** occurs on conversion. – Aconcagua Jul 09 '20 at 06:18
1
I think this is a nice implementation:
template <class T, class U>
void swap_2t (T& t, U& u)
{
const T tmp = t;
t = static_cast<T>(u);
u = static_cast<U>(tmp);
}

Ali Askari
- 515
- 3
- 8