swapping in one line statement in c c++ language.
For further actions, you may consider blocking this person and/or reporting abuse
swapping in one line statement in c c++ language.
For further actions, you may consider blocking this person and/or reporting abuse
ANIRUDDHA -
Anurag choudhary -
Deborah -
Ian Ndeda -
Top comments (4)
Using
*
especially has a risk of causing overflow, which is undefined behavior. (Unsigned overflow is not defined, but(x * y) / y
is not alwaysx
in unsigned arithmetic). The+
option is better, but can still overflow. A better option would be^
(xor), since there's no overflow possible.However, while this solution is cute, it's still undefined behavior. You're not allowed to both read and write a variable within one expression, because there's no specified sequence determining which happens first. It might happen to work in this example on the compiler you're using, but with optimizations enabled any number of things could break it. (Both gcc and clang rightfully emit a warning when you try this code).
In C++, you should use
std::swap(a, b)
.You can define your own
swap
macro in C if you really need it, for example from this StackOverflow question:yeah but we have to do need inline swapping statement so is it best.
The code you have shared in the post is wrong for multiple reasons, as outlined above. As a result, it doesn't even solve the problem, let alone be the best solution.
may be but According to placement or viva exam Interview may ask online statement swapping statement.