I’m exploring inline assembly in Zig, but I have a compiler error.
I’m using Zig version 0.15.2
The goal is to create a swap function without creating a temporary variable like this:
fn swap(x: *u32, y: *u32) void {
x.* ^= y.*;
y.* ^= x.*;
x.* ^= y.*;
}
I tried writing this, but in assembly for educational purposes. I’m not certain that the logic is correct, because I haven’t tested it. It does not compile.
fn swap32(x: *u32, y: *u32) void {
asm volatile (
\\ xord %[eax], %[ebx]
\\ xord %[ebx], %[eax]
\\ movd %[eax], %[x]
\\ xord %[eax], %[ebx]
\\ movd %[ebx], %[y]
: [x] "{eax}" (x),
[y] "{ebx}" (y),
);
}
The documentation on inline assembly is sparse, so I’ll just say what I’m trying to do. I’m trying to load x into eax and y into ebx. Then, the operations are pretty clear. The error I get is this:
~/software/MISC/zig/generic_swap > zig build-exe generic_swap.zig
generic_swap.zig:20:5: error: asm cannot output to const local 'x'
asm volatile (
^~~
So, I’m thinking something is really wrong with what I’m doing. Any insights?