Swap variable without arithmatic..

Discussion in 'C' started by vatsa_mitr, Sep 10, 2006.

  1. vatsa_mitr

    vatsa_mitr New Member

    Joined:
    Sep 2, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi all,
    It might b an old question but how can i swap two variables without applying any arithmatic operation...
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,355
    Likes Received:
    383
    Trophy Points:
    83
    This can be done by applying any 2 operations that are are opposite to each other in nature like + and - * and /. The above are arithmetic operations and so if you cant use them you need to be doing either shifting or using the & / | to achieve the same

    Code:
    a = a OP1 b 
    b = a OP2 b
    a = a OP2 b
    OP1 and OP2 are opposite operations but I am not sure you can use the << and >> as there you loose one bit so you should be going with boolean operation.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice