+ 2

How to swap 2 numbers using a single semiconlon only in C or C++ without using swap function?

24th Oct 2017, 11:34 AM
Rahul Chaturvedi
Rahul Chaturvedi - avatar
9 Respostas
+ 4
a^=b^=a^=b; This one line swap any data type values as it is a binary swap
24th Oct 2017, 4:33 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 3
oh really ? I did not know
24th Oct 2017, 6:42 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
Noone said the numbers can't be in an array. https://code.sololearn.com/cI9VW8XMV5v6/?ref=app
24th Oct 2017, 1:25 PM
deFault
+ 1
You need atleast 3, whether you use a temp variable, apply XOR on the variables or addition and subtraction, or address assignments. If you wish to use a one liner, std::swap() is the way to do so. Nothing else is there. Edit : Wrongly said. Sorry.
24th Oct 2017, 11:50 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
@Baptiste, Also, it results in undefined behaviour (at least in pre c++17), as a and b are modified more then once in one sequence point. I wrote about a similar case recently here: https://www.sololearn.com/discuss/807745/?ref=app
24th Oct 2017, 11:15 PM
deFault