DEV Community

Pykash
Pykash

Posted on

swapping in one line

swapping in one line statement in c c++ language.

Top comments (4)

Collapse
 
curtisfenner profile image
Curtis Fenner

Using * especially has a risk of causing overflow, which is undefined behavior. (Unsigned overflow is not defined, but (x * y) / y is not always x 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:

#define swap(T, x, y) {T _swap_tmp = x; x = y; y = _swap_tmp; }
Collapse
 
pykashchain profile image
Pykash

yeah but we have to do need inline swapping statement so is it best.

Collapse
 
curtisfenner profile image
Curtis Fenner

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.

Thread Thread
 
pykashchain profile image
Pykash

may be but According to placement or viva exam Interview may ask online statement swapping statement.