Author Topic: Swap Function  (Read 847 times)

0 Members and 1 Guest are viewing this topic.

Nicola

  • Guest
Swap Function
« on: January 02, 2021, 09:02:50 AM »
Hello,
i was seeing and trying some swap functions (value swapping between two variables).
The attached listing gives an example and use.

Code: OxygenBasic
  1. 'Swap functions
  2. 'hello from Nicola
  3. '-----------------
  4. use console
  5.  
  6. sub pprint(string s,a,b)  'serve per stampare i dati
  7.  printl "Using " + s +"  "+a + "  "+ b
  8. end sub
  9.  
  10. function swap(int *a, int *b)
  11.         local int c=a
  12.         a=b :   b=c
  13. end function
  14.  
  15. macro swapp(a,b) 'funziona per qualsiasi tipo di dato
  16.  typeof a v=a
  17.   a=b : b=v
  18. end macro
  19.  
  20. macro swaps(a,b) 'funziona x qualsiasi dato.
  21.  dim as string v(2)={a,b}
  22.   a=v(2) : b=v(1)
  23. end macro
  24.  
  25. macro swapar(a,b) 'swap usando il + e il -
  26.  a=a+b
  27.   b=a-b
  28.   a=a-b
  29. end macro
  30.  
  31. macro swaper(a,b) 'swap usando il * e il /
  32.  a=a*b
  33.   b=a/b
  34.   a=a/b
  35. end macro
  36.  
  37. macro swapxor(a,b) 'swap usando il * e il / funziona per soli int
  38.  a=a xor b
  39.   b=a xor b
  40.   a=a xor b
  41. end macro
  42.  
  43.  
  44. int a=20, b=35
  45. pprint("Before  ",a,b)
  46. swap(a,b)
  47. pprint("swap    ",a,b)
  48. swapar(a,b)
  49. pprint("swapar  ",a,b)
  50. swaper(a,b)
  51. pprint("swaper  ",a,b)
  52. swapxor(a,b)
  53. pprint("swapxor ",a,b)
  54. swaps(a,b)
  55. pprint("swaps   ",a,b)
  56.  
  57. float a=1.5,b=2.5
  58. pprint("Before  ",a,b)
  59. swapp(a,b)
  60. pprint("swapp   ",a,b)
  61. swapar(a,b)
  62. pprint("swapar  ",a,b)
  63. swaper(a,b)
  64. pprint("swaper  ",a,b)
  65. 'swapxor(a,b)              'non funziona per float
  66. 'pprint("swapxor ",a,b)
  67. swaps(a,b)
  68. pprint("swaps   ",a,b)
  69.  
  70. string h="Nicola", k="Charles"
  71. swapp(h,k)
  72. pprint("swapp   ",h,k)
  73. swaps(h,k)
  74. pprint("swaps   ",h,k)
  75.  
  76. waitkey
  77.  
« Last Edit: January 07, 2021, 12:23:40 PM by Nicola »

Charles Pegge

  • Guest
Re: Swap Function
« Reply #1 on: January 07, 2021, 04:08:54 AM »
Thanks Nicola.

The swap macro will cover most situations efficiently.

Macros often have significant advantages over procedures/functions, supporting multiple types and avoiding the overhead of making calls.