DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
 
zhu48 profile image
Zuodian Hu • Edited

Very contrived, only works on ARM, not even acceptable by all C compilers, but you never constrained the problem that way!

void swap(int* a, int* b) {
    __asm volatile (
        "MOV R2, R1 \n"
        "MOV R1, R0 \n"
        "MOV R0, R2 \n"
    );
}
Collapse
 
zhu48 profile image
Zuodian Hu

Oh and as prplz mentioned, any self-respecting compiler nowadays will use only registers any way you decide to implement this little stub of a function. Yes yes, the question is very contrived too, but hey.

Collapse
 
theoutlander profile image
Nick Karnik • Edited

Aren't you using a third register though?

Are you're thinking that you can do that because it's not in RAM?

Thread Thread
 
zhu48 profile image
Zuodian Hu

The way the question is formulated, you're limited by having a certain amount of memory. Any register use doesn't count against that at all.

Collapse
 
zhu48 profile image
Zuodian Hu

I went to bed, and realized that my answer is wrong. Exchanging the values in register is completely invisible to the function caller. Here's the correct answer.

void swap(int* a, int* b) {
    __asm volatile {
        "LDR R2, [R0] \n"
        "LDR R3, [R1] \n"
        "STR R2, [R1] \n"
        "STR R3, [R0] \n"
    }
}

Further, as R0-R3 are all caller-save registers in the ARM ABI, the function body, excluding the function entry stack shenanigans, uses zero memory.