Ady Wicaksono Daily Activities

Swap 2 variables without temporary variables?

with 3 comments

This is the solution:

#include <stdio.h>

void swap(int *x, int *y){
  *x -= *y;
  *y += *x;
  *x  = (*y - *x);
}

int main(){
   int a = 100;
   int b = 200;
   printf("a = %dnb = %dn",a,b);
   swap(&a,&b);
   printf("a = %dnb = %dn",a,b);
   return 0;
}

Written by adywicaksono

July 10, 2007 at 4:55 pm

Posted in Programming

3 Responses

Subscribe to comments with RSS.

  1. Cara mas ady ini ada proses tambahan, yaitu 2x substraction dan 1x addition.
    Kl menggunakan cara dengan temporary variabel swap, tidak ada proses substraction dan addition.
    So, Process VS Memory, jika ingin proses sederhana, maka dibutuhkan memory lebih banyak, dan sebaliknya.
    Dari segi kecepatan eksekusi (meskipun tidak terasa oleh kita), menurut saya lebih cepat yg menggunakan temporary variable. Karena cuman ada proses assignment (mov). Kl addition dan substraction, selain proses assigment, ada proses aritmatika.

    addiehz

    July 13, 2007 at 1:19 am

  2. Be careful when using this for production code. Read this:

    http://prabhagovind.wordpress.com/2007/02/09/3-ways-to-swap-variables-without-temp-variable/

    addiehz is correct: this method is slower, but he was a bit wrong about the additional memory needed for the temporary variable.

    The usual method using temp variable, doesn’t require more memory, because the compiler can optimize using register. Just try out creating simple swap function using temporary variable, compile with high optimization, and generate the assembler code (in gcc: gcc -O3 -S swap.c).

    Yohanes

    July 14, 2007 at 8:28 am

  3. ups.. nyasar di sini.. ga tau masalah memori-memori an se.. tp stidaknya dah nyoba ndobrak doktrin selama ini.. hehehe…

    defindal

    July 15, 2007 at 2:37 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: