Is there a built in swap function in C?

前端 未结 11 2157
北恋
北恋 2020-12-15 16:01

Is there any built in swap function in C which works without using a third variable?

11条回答
  •  执念已碎
    2020-12-15 16:38

    Why do you not want to use a third variable? It's the fastest way on the vast majority of architectures.

    The XOR swap algorithm works without a third variable, but it is problematic in two ways:

    1. The variables must be distinct i.e. swap(&a, &a) will not work.
    2. It is slower in general.

    It may sometimes be preferable to use the XOR swap if using a third variable would cause the stack to spill, but generally you aren't in such a position to make that call.

    To answer your question directly, no there is no swap function in standard C, although it would be trivial to write.

提交回复
热议问题