Is there a built-in way to swap two variables in C

后端 未结 10 1546
夕颜
夕颜 2020-12-01 14:53

I know how to swap 2 variables in c++ , ie you use std::swap(a,b).

question:

Does the C standard library have a similar function

10条回答
  •  [愿得一人]
    2020-12-01 15:21

    In case of numeric values (at least):

    I know this is not an actual or complete answer but until now everyone has been making use of temporary variables so I thought Chris Taylors blog might be relevant to mention, it certainly does remove the need for typeof() etc.

    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    

    or

    a = a + b;
    b = a - b;
    a = a - b;
    

    In theory I suppose these techniques could be applied to strings and other types as well..

    Still only three operations.

提交回复
热议问题