Wendi Zhang
Wendi Zhang

Reputation: 29

Using inline assembly to swap two integer variables

(editor's note: this is a debugging question about what's wrong with this attempted implementation (nearly everything), and thus not a duplicate of How to write a short block of inline gnu extended assembly to swap the values of two integer variables? But see that Q&A and https://stackoverflow.com/tags/inline-assembly/info if you want a working example.)


I'm trying to swap two integer variables using gnu extended assembly, here's what I have for now:

int main()
{
    int a = 2;
    int b = 1;
    printf("a is %d, b is %d\n", a, b);
    // TODO (student): swap a and b using inline assembly
    printf("a is %d, b is %d\n", a, b);
    asm ("mov ebx, b;"
        "mov ecx, b;"
        "mov c, ecx;"
        "mov d, ebx;"
    );

I get the error message: asmPractice.c:17: Error: too many memory references for mov.

How do I solve this?

Upvotes: 1

Views: 1527

Answers (3)

Andreas DM
Andreas DM

Reputation: 10998

Using extended inline assembly syntax, this is a one-liner:

volatile int a = 1;
volatile int b = 2;

asm("" : "=r" (a), "=r" (b) : "0" (b), "1" (a) : );
//      ^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^
//           input               output

printf("a is %d, b is %d\n", a, b);

Upvotes: 3

Edil
Edil

Reputation: 14

Try put double % before register.

Upvotes: -1

Brighter side
Brighter side

Reputation: 402

Don't know if it matters. But in my remember, you need to put % before register call in order to make the interpreter understand you speak about register. Like mov %esp, %ebp

Try it but not 100% sure will fix it. asm in C "too many memory references for `mov'" refering to this post

Upvotes: 0

Related Questions