Write a c program to add two numbers using assembly code.

Ram Pothuraju

 #include <stdio.h>


int main()

{

    int num1, num2, sum;


    printf("Enter two integers separated by a space: ");

    scanf("%d %d", &num1, &num2);


    // Inline assembly code to add num1 and num2

    __asm__ (

        "movl %1, %%eax;"

        "addl %2, %%eax;"

        "movl %%eax, %0;"

        : "=r" (sum)

        : "r" (num1), "r" (num2)

        : "%eax"

    );


    printf("The sum of %d and %d is %d\n", num1, num2, sum);


    return 0;

}



In this program, we use inline assembly code to perform the addition of num1 and num2. The movl instruction moves the value of num1 into the eax register, the addl instruction adds the value of num2 to the eax register, and the movl instruction moves the result back into the sum variable. The input and output operands are specified using the input/output constraints in the extended inline assembly syntax.

Note that inline assembly code is not portable across different platforms or compilers, and should be used with caution. It is generally recommended to use C code to perform arithmetic operations instead.

Post a Comment

0Comments

Post a Comment (0)