home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!news.univie.ac.at!scsing.switch.ch!ira.uka.de!slsvaat!josef!kanze
- From: kanze@us-es.sel.de (James Kanze)
- Subject: Re: Help w/ default arguments and more
- In-Reply-To: ski8032@tamsun.tamu.edu's message of 22 Jan 1993 18:41:09 -0600
- Message-ID: <KANZE.93Jan28171214@slsvdnt.us-es.sel.de>
- Sender: news@us-es.sel.de
- Organization: SEL
- References: <1jq475INNp69@tamsun.tamu.edu>
- Date: 28 Jan 93 17:12:14
- Lines: 45
-
- In article <1jq475INNp69@tamsun.tamu.edu> ski8032@tamsun.tamu.edu
- (Suman Kumar Inala) writes:
-
- |> Also, I know I'm missing
- |> something simple here, but the following doesn't work:
-
- |> #define SWAP_INT(a, b) { a ^= b; b ^= a; a ^= b; }
- |> inline void swap(int a, int b) { a ^= b; b ^= a; a ^= b; }
-
- |> The SWAP_INT macro works, but not my inline function. Why?
-
- The inline macro would work better if you declared the parameters as
- references, ie:
-
- inline void swap( int& a , int& b ) ...
-
- But in fact, neither the inline nor the macro work if you're swaping a
- value with itself, ei:
- SWAP_INT( x , x )
-
- Of course, no one would write this intentionally, but it will
- occasionally pop up in algorithms to inverse arrays, sorting, etc.
- (The programmer may decide that doing one swap too many in some
- special cases is less expensive than adding an extra test in a tight
- loop.)
-
- This is difficult to avoid with the macro, but try the following
- inline function:
-
- inline void
- swap( int& a , int& b )
- {
- int tmp = a ;
- a = b ;
- b = tmp ;
- }
-
- This should work in all cases, and in addition, will typically be
- faster (at run-time) than the posted algorithm. (Any compiler worth
- its salt will get tmp into a register.)
- --
- James Kanze email: kanze@us-es.sel.de
- GABI Software, Sarl., 8 rue du Faisan, F-67000 Strasbourg, France
- Conseils en informatique industrielle --
- -- Beratung in industrieller Datenverarbeitung
-