C - fastest method to swap two memory blocks of equal size?

前端 未结 9 2570
春和景丽
春和景丽 2021-02-20 05:20

What is the fastest way to swap two non-overlapping memory areas of equal size? Say, I need to swap (t_Some *a) with (t_Some *b). Considering space-tim

9条回答
  •  隐瞒了意图╮
    2021-02-20 06:17

    Thought I'd share my simple solution I've been using for ages on micro controllers without drama.

    #define swap(type, x, y) { type _tmp; _tmp = x; x = y; y = _tmp; }
    

    OK... it creates a stack variable but it's usually for uint8_t, uint32_t, float, double, etc. However it should work on structures just as well.

    The compiler should be smart enough to see the stack variable can be swapped for a register when the size of the type permits.

    Really only meant for small types... which will probably suit 99% of cases.

    Could also use "auto" instead of passing the type... but I like to be more flexible and I suppose "auto" could be passed as the type.

    examples...

    swap(uint8_t, var1, var2) 
    swap(float, fv1, fv2)
    swap(uint32_t, *p1, *p2) // will swap the contents as p1 and p2 are pointers
    swap(auto, var1, var2) // should work fine as long as var1 and var2 are same type
    

提交回复
热议问题