[Adobe]generic swap macro in c

write a generic swap macro in c that can be used for swapping int ,char,float,double and even pointers.

Comments

  1. void swap(void *a, void *b, size_t size)
    {
    char *ca, *cb;
    int i;
    ca = (char *)a;
    cb = (char *)b;
    for(i=0;i<size;*(ca+i)^=*(cb+i),*(cb+i)^=*(ca+i),*(ca+i)^=*(cb+i),++i);
    }
    void pointer can be used to store any kind of address,it is typecasted to char pointer so that one byte at a time can be swapped.

    ReplyDelete
  2. /* Generic Swap macro*/
    #define swap(a, b, type) { type t = a; a = b; b = t; }

    ReplyDelete
  3. #define Swap(X,Y) { __typeof__ (X) T = X; X = Y; Y = T; }
    int main()
    {
    int a=10,b=20;
    Swap(a,b);
    printf("%d %d",a,b);
    return 0;
    }

    __typeof__ is a GNU C extension so we don't even need to pass type as third parameter.but it will be portability issue.

    ReplyDelete
  4. /* Generic Swap macro*/
    #define swap(a, b, type) { type t = a; a = b; b = t; }

    will not run .. try it... and try to find the reason :)

    ReplyDelete

Post a Comment

Popular posts from this blog