Swap Values of two Variables

Hi there,

if you want to swap the value of two Variables without using a third temporary one, heres how:

Lets say you have Variables “a = 5” and “b = 15” and you want to swap them,
so its “a = 15”, “b = 5”.

You could use a third “temporary” variable to do it like this:

temp := b;
b := a;
a := temp;

another way, without the necessity of the “temp” Variable is:
Using XOR to swap the bits of the two variables.
After three XOR “swaps” the value-Swap is done:

a := a XOR b;
b := a XOR b;
a := a XOR b;

I have put it in a function, if anyone is interested. In this case for Variables of type “INT”

FUNCTION f_swapInt : USINT
	VAR_IN_OUT
		a : INT;
		b : INT;
	END_VAR
END_FUNCTION
(* Swaps the Value of 2 Integer Variables *)
FUNCTION f_swapInt
	a := a XOR b;
	b  := a XOR b;
	a := a XOR b;
END_FUNCTION
3 Likes

First line of code with temp variable should be :
temp := b;

Otherwise both variables will remain with the initial “a” value.

The XOR swap works well. :wink:

1 Like