Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't a swap / exchange operator exist in imperative or OO languages like C/C++/C#/Java...?

I was always wondering why such a simple and basic operation like swapping the contents of two variables is not built-in for many languages.

It is one of the most basic programming exercises in computer science classes; it is heavily used in many algorithms (e.g. sorting); every now and then one needs it and one must use a temporary variable or use a template/generic function.

It is even a basic machine instruction on many processors, so that the standard scheme with a temporary variable will get optimized.

Many less obvious operators have been created, like the assignment operators (e.g. +=, which was probably created for reflecting the cumulative machine instructions, e.g. add ax,bx), or the ?? operator in C#.

So, what is the reason? Or does it actually exist, and I always missed it?

like image 628
mr_georg Avatar asked Nov 13 '08 08:11

mr_georg


3 Answers

In my experience, it isn't that commonly needed in actual applications, apart from the already-mentioned sort algorithms and occasionally in low level hardware poking, so in my view it's a bit too special-purpose to have in a general-purpose language.

As has also been mentioned, not all processors support it as an instruction (and many do not support it for objects bigger than a word). So if it were supported with some useful additional semantics (e.g. being an atomic operation) it would be difficult to support on some processors, and if it didn't have the additional semantics then it's just (seldom used) synatatic sugar.

The assigment operators (+= etc) were supported because these are much more common in real-world programs - and so the syntacic sugar they provide was more useful, and also as an optimisation - remember C dates from the late 60s/early 70s, and compiler optimisation wasn't as advanced (and the machines less capable, so you didn't want lengthy optimisation passes anyway).

Paul

like image 197
The Archetypal Paul Avatar answered Oct 07 '22 15:10

The Archetypal Paul


C++ does have swapping.

#include <algorithm>
#include <cassert>

int
main()
{
    using std::swap;
    int a(3), b(5);
    swap(a, b);
    assert(a == 5 && b == 3);
}

Furthermore, you can specialise swap for custom types too!

like image 39
Chris Jester-Young Avatar answered Oct 07 '22 14:10

Chris Jester-Young


It's a widely used example in computer science courses, but I almost never find myself needing it in real code - whereas I use += very frequently.

Yes, in sorting it would be handy - but you don't tend to need to implement sorting yourself, so the number of actual uses in source code would still be pretty low.

like image 28
Jon Skeet Avatar answered Oct 07 '22 15:10

Jon Skeet