DEV Community

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

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.