Skip to content

Instantly share code, notes, and snippets.

@marsgpl
Created May 29, 2025 06:58
Show Gist options
  • Save marsgpl/042825e0d644312c1dc1cfaa44432d29 to your computer and use it in GitHub Desktop.
Save marsgpl/042825e0d644312c1dc1cfaa44432d29 to your computer and use it in GitHub Desktop.
Write a Program in C to Swap the values of two variables without using any extra variable.
#include <stdio.h>
int main() {
int a = 123123123;
int b = 456456456;
printf("before swap: a = %d b = %d\n", a, b);
// other swap options:
// asm xchg (only x86)
// asm 3 movs (non-atomic)
// arithmetic (xor, +/-, mul/div etc) (non-atomic)
__asm__ (
"mov %w2, %w0\n" // w2=w0 - use extra registry to backup w0 value
"mov %w0, %w1\n" // w0=w1
"mov %w1, %w2\n" // w1=w2
: "+r" (a), "+r" (b) // put a into %w0 and b into %w1
);
printf("after swap: a = %d b = %d\n", a, b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment