Sunday, November 21, 2010

How to swap two variables without using a third variable ?

#include <stdio.h>
int main()
{
    int m=10,n=15;
    printf(“Before swapping: m=%d, n=%d\n”,m,n);
    m=m^n;
    n=n^m;
    m=m^n;
    printf(“After swapping: m=%d, n=%d\n”,m,n);
    return 0;
}

Explanation:

The operator here used is (^) bit wise exclusive OR operator.  The truth table of exclusive OR is as:

Operator 1
Operator 2
Output
0
0
0
0
1
1
1
0
1
1
1
0


Convert the numbers from decimal system to binary system and then apply the logic.

Advantage:

It does not occupy a third variable and hence memory consumption is less. This is more advantageous while swapping two strings. The strings occupy memory a lot. Copying one string to other takes CPU cycles as well. Using pointer and union we can optimize both memory and CPU cycle consumption.
Refer below program:

//Program by Nikunj Master, Eleiss
#include<stdio.h>
#include<stdlib.h>

union memory
{
        char *ptr;
        int addr;
};

int main()
{
        union memory m1,m2;
        m1.ptr=(char*)malloc(100*sizeof(char));
        m2.ptr=(char*)malloc(100*sizeof(char));
        printf("Scan two strings\n");
        scanf("%s %s",m1.ptr,m2.ptr);
        printf("Before swapping: m1=%s, m2=%s\n",m1.ptr,m2.ptr);
        m1.addr=m1.addr^m2.addr;
        m2.addr=m2.addr^m1.addr;
        m1.addr=m1.addr^m2.addr;
        printf("After swapping: m1=%s, m2=%s\n",m1.ptr,m2.ptr);
        return 0;
}

Sunday, October 10, 2010

Union in C

Union is one of the coolest properties of C. Union is used to group a number of variables of different type in single unit like structure does.

But the differences between structure and union are:
  • While a structure enables us to treat the unit as a number of different variables stored at different places in memory, a union enables us to treat the same space in memory as a number of different variables. i.e a union permits a section of memory to be treated as a variable of one type on one occasion, ans as a different variable of a different type on another occasion.
  • A union allocates the memory equal to the maximum memory required by the member of the union while a  structure allocates the memory equal to the total memory required by the members.
  • In union, one block is used by all the member of the union but in case of structure, each member have their own memory space.
Syntax:
union test
{
      char var1;
      int var2;
      float var3;
};

example:
//union.c - A program demonstrating the concept of union
//By Nikunj Master, Eleiss
#include <stdio.h>
union test
{
      char a;
      int b;
};
int main()
{
      union test t;
      t.b=100;
      printf("t.a:%c, t.b:%d\n",t.a,t.b);
      return 0;
}

Compile the above program as:
gcc -g union.c -o union

Run as:
./union

Output:
t.a:d, t.b:100