Variable swapping question

Discussion in 'C Programming' started by Chad, Jul 5, 2008.

  1. Chad

    Chad Guest

    Given something like the following

    void swap(int *x, int *y)
    int temp;

    temp = *x;
    *x = *y;
    *y = temp;

    How does having a temp variable allow for anything to safely swap with
    itself? Like for example x = 10 and y = 10. What would happen in the
    absence of temp?

    Chad, Jul 5, 2008
    1. Advertisements

  2. I assume you mean *x == 10 and *y == 10.

    But what I suspect you *really* mean is x == y, i.e., x and y both
    point to the same object. The swap function above works just fine in
    that case; the value is saved to temp, then copied over itself, then
    restored from temp. Is there some potential problem you had in mind?
    Well, you couldn't do the first and third assignments, so it wouldn't
    be able to swap anything. Or did you have something else in mind
    instead of temp? Perhaps something like question 3.3b of the
    comp.lang.c FAQ, <>?
    Keith Thompson, Jul 5, 2008
    1. Advertisements

  3. Chad

    Chad Guest

    I was just curious why you needed temp. I did the following

    m-net% more swap.c
    #include <stdio.h>
    void swap(int *x, int *y)
    int temp;

    /*temp = *x ; */
    *x = *y;
    /* *y = temp; */


    int main(void)
    int a = 10;
    int b = 20;

    swap(&a, &b);

    printf("After swap: a=%d , b=%d\n", a, b);

    return 0;
    m-net% ./swap
    After swap: a=20 , b=20

    And now just thought about what you said. Now I need about a hour for
    it to really sink in.
    Chad, Jul 5, 2008
  4. Chad

    Ron Ford Guest

    I see no mystery in this result; you'll find that this type of swap needs a
    temp. You can swap in other ways, say, using a macro, but the pointer
    version is simply better all around.
    Ron Ford, Jul 5, 2008
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.