Skip to content

Instantly share code, notes, and snippets.

@shellmonk
Created October 3, 2023 22:15
Show Gist options
  • Save shellmonk/0b53c8723b9bef8c4c763946a3201d99 to your computer and use it in GitHub Desktop.
Save shellmonk/0b53c8723b9bef8c4c763946a3201d99 to your computer and use it in GitHub Desktop.
Swap values of two integer variables without introducing the third one - inline assembly abuse edition
/**
* PROBLEM:
* Swap values of two integer
* variables without introducing
* the third one
*
* $ gcc -o swap swap.c
* $ chmod +x swap
* $ ./swap
*
*/
#include <stdio.h>
int main() {
int a = 69;
int b = 420;
printf("a = %d; b = %d", a, b);
asm ("xchg %0, %1\n" : "=r" (a) : "r" (b));
printf("a = %d; b = %d", a, b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment