CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Apr 2003
    Location
    Pakistan
    Posts
    42

    interchange of variables

    Hi all, this is a pretty simple question but has been haunting me for quite sometime now so here goes....How is it possible to interchange the values of two variables without having to store one of their value temporarily? Need an answer quick!

    Thanx in advance
    Awais
    Life is what happens to you while you're busy making other plans!

  2. #2
    Join Date
    Dec 2001
    Location
    Bremen, Germany
    Posts
    314

    Re: interchange of variables

    Use pointers and swap them instead of the variable values

  3. #3
    Join Date
    Mar 2004
    Location
    Israel
    Posts
    638
    consider:
    A = 2;
    B = 8;

    A=A+B; ==> now A=10, B=8
    B=A-B; ==> now A=10, B=2
    A=A-B; ==> now A=8, B=2

    Regards,
    Guy
    **** **** **** **** **/**

  4. #4
    Join Date
    Oct 2003
    Location
    Romania
    Posts
    127

    Re: Re: interchange of variables

    Originally posted by Oliver Twesten
    Use pointers and swap them instead of the variable values
    ... and furthermore, use only those pointers, because each variable remains in its initially place.

  5. #5
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,150
    What kind of variables do you want to swap?
    If these are numeric variables, you can use the xor-swap method:
    Code:
    // swap x and y
    x ^= y;
    y ^= x;
    x ^= y;
    or directly use the XCHG i386 opcode
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

  6. #6
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652
    [Merged threads]

  7. #7
    Join Date
    Jun 2004
    Posts
    14
    swap(A,B);

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured