Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!apple!oliveb!amdahl!twg-ap!dwh From: dwh@twg-ap.UUCP (Dave Hamaker) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: <362@twg-ap.UUCP> Date: 8 Sep 89 01:31:33 GMT References: <922@kim.misemi> Organization: The Wollongong Group, Palo Alto, CA. Lines: 49 From article <922@kim.misemi>, by kim@kim.misemi (Kim Letkeman): > I hope that all of this talk about swapping two values without a > temporary is just for fun ... > > When one writes clean, easy to read code, this sort of idea never > occurs. Simply using a temporary location makes it obvious what is > going on. It would be silly to have to actually comment something as > trivial as "here I am swapping two values". Whenever _I_ write code for swapping two values, this idea _always_ occurs, and I usually decide not to apply it. Does this mean I write dirty, hard to read code? I can also assure you that every piece of code you've ever written would be hard to read -- for my five-year-old daughter. The position that good programming is a matter of following the right set of moralistic rules is, in my view, oversimplified to the extent of being simply wrong. Good writing generally requires: 1) Knowing your subject. 2) Knowing the language. 3) Knowing your audience. 4) As well as knowing principles of "clear" writing. When you write a program, you have more than one audience. You are writing for at least one machine, for at least one compiler (if you use a high-level language), as well as for those people who will read it later (including yourself). If you aim too low for the people audience, you may find that the people who really read your code may find it "cluttered" with trivial comments. You might even be accused of wasting your time writing them. If you ignore your other audiences, there's nothing wrong with always choosing the algorithm which is easiest to explain. The exclusive-or technique for exchanging two data items really falls in the area of knowing your subject. It's part of understanding the uses of bitwise logical operations, which is important for some kinds of program- ming. I can easily imagine a few cases where it might be the "right" solution to a programming problem, although the trick is obscure enough that uncommented use of it is probably always wrong. If we're going to look at generated code, it might be instructive to see what happens if x and y are declared to be "register" (I say this without actually knowing what will come out of the compiler). -Dave Hamaker The Wollongong Group ...!sun!amdahl!twg-ap!dwh dwh@twg.com