Thread: Swap two variables with out third variable

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    1

    Swap two variables with out third variable

    Hi All,

    I am C newbie ,my question is How Swap two variables with out third variable ?

    and also i am looking for the online resources on Exercises for C programming .


    Kanthi

  2. #2
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    Do a web search for xor swap.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    5
    Hi Kanthi,

    Swapping 2 variables is possible as follows:

    x = x + y
    y = x - y
    x = x - y

    Although this way doesn't require a third variable, but it is not simple to understand. So I think it is not good to use this way.


    K.n.i.g.h.t

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Please stop colouring your posts and centering all your text.

    Not to mention the fact that your solution breaks down if arithmetic overflow or underflow happens.

    Check the replies of those who have a clue here
    http://cboard.cprogramming.com/showt...swap+variables
    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. swap of variables without tmp
    By ZaC in forum C Programming
    Replies: 16
    Last Post: 06-13-2009, 02:28 PM
  2. changing the address of a pointer question..
    By transgalactic2 in forum C Programming
    Replies: 42
    Last Post: 10-16-2008, 09:20 AM
  3. Variable Call via Another Variable's Content
    By E-Rac in forum C++ Programming
    Replies: 2
    Last Post: 01-18-2005, 01:51 PM
  4. Beginner question
    By Tride in forum C Programming
    Replies: 30
    Last Post: 05-24-2003, 08:36 AM
  5. Variable Allocation in a simple operating system
    By awkeller in forum C Programming
    Replies: 1
    Last Post: 12-08-2001, 02:26 PM