home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / lang / cplus / 20055 < prev    next >
Encoding:
Text File  |  1993-01-28  |  1.9 KB  |  58 lines

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