I am very new to assembly, and the code below should exchange two integers for two different functions: first use swap_c and then using swap_asm .
However, I doubt whether I need to push (I mean saving) each value of the registers before the assembly code and pop them later (just before returning to main ). In other words, will I be angry with me if I return to other registered content (not as key as ebp or esp , but just eax , ebx , ecx and edx )) after running the swap_asm function? Is it better to uncomment the lines in the assembly?
This code works fine for me, and I managed to reduce 27 lines of assembled C code to 7 assembly lines.
ps: The system is Windows 10, VS-2013 Express.
main.c part
#include <stdio.h> extern void swap_asm(int *x, int *y); void swap_c(int *a, int *b) { int t = *a; *a = *b; *b = t; } int main(int argc, char *argv[]) { int x = 3, y = 5; printf("before swap => x = %dy = %d\n\n", x, y); swap_c(&x, &y); printf("after swap_c => x = %dy = %d\n\n", x, y); swap_asm(&x, &y); printf("after swap_asm => x = %dy = %d\n\n", x, y); getchar(); return (0); }
assembly.asm part
.686 .model flat, c .stack 100h .data .code swap_asm proc ; push eax ; push ebx ; push ecx ; push edx mov eax, [esp] + 4 ; get address of "x" stored in stack into eax mov ebx, [esp] + 8 ; get address of "y" stored in stack into ebx mov ecx, [eax] ; get value of "x" from address stored in [eax] into ecx mov edx, [ebx] ; get value of "y" from address stored in [ebx] into edx mov [eax], edx ; store value in edx into address stored in [eax] mov [ebx], ecx ; store value in ecx into address stored in [ebx] ; pop edx ; pop ecx ; pop ebx ; pop eax ret swap_asm endp end