In awk, without needing a temp variable, a temp array, an external function call, substring-ing their values out of one another, XOR operations, or even any math operations of any sort,
this trick works for whether their values are numeric, string, or even arbitrary bytes that aren't UTF8-compliant, nor do the types of the 2 variables even need to match :
gawk/mawk/nawk '{
a = (b) \
substr("", ( b = (a) )^"")
}'
Even in Unicode-locale, gawk unicode mode could swap the values of arbitrary non-UTF8 bytes without any error messages.
No need to use C or POSIX locale.
Why it works is that in the process of this concatenation, the original value of b has already been placed in some system-internal staging ground, so the sub-sequent assignment of b's value into a does not have any impact into what's being assigned into a
The second half of it is taking a substring of an empty string, so of course nothing comes out, and doesn't affect the first half.
After b = a, I immediately take the zero-th power of it, which always returns a 1 in awk
so the latter portion becomes
# in awk, string indices start from 1 not 0
substr(EMPTY_STRING, STARTING-POSITION-OF-ONE)
of course nothing comes out of it, which is the desired effect, so the clean original value of b could be assigned into a.
This isn't taking a substring of a's or b's value. It's taking advantage of dynamic typing properties of awk.
A XOR-based approach, which clean, still require 3 operations, plus a safety check against being memory position (for C). And for gnu-awk, its xor() function only works with non-negative numeric inputs.
This one-liner approach circumvents all the common issues with value swapping.
Either a or b, or even both, being an array cell, regardless of single or multi-dimensional, e.g.
arr[ _pos_idx_a_ ]
works exactly the same with this one-liner approach. The only limitation I could think of is that this approach cannot directly swap full contents of an entire array with another array.
I thought of adding a check for a==b to avoid a double assignment, but then realized the internal system resources needed to perform such a check is not worth the minuscule amount of time saved.