4.
This is not really an mistake but an oversight which can cause some hard to catch errors.Here is the program
#include<stdio.h>
#include<conio.h>
#include<limits.h>
int main()
{
int a=10,b=20;
printf("Before swap a=%d b=%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("After swap a=%d b=%d\n",a,b);
_getch();
return 0;
}
It basically swaps two variables without using a third variable.The program runs fine and prints "a=20 b=10" after swapping.So where is the problem?Lets have another look at this program but we will be using different values this time
#include<stdio.h>
#include<conio.h>
#include<limits.h>
int main()
{
int a=INT_MAX,b=20;
printf("Before swap a=%d b=%d\n",a,b);
a=a+b;
printf("After a=a+b a=%d b=%d\n",a,b);
b=a-b;
printf("After b=a-b a=%d b=%d\n",a,b);
a=a-b;
printf("After swap a=%d b=%d\n",a,b);
_getch();
return 0;
}
Here is the output from console
Before swap a=2147483647 b=20
After a=a+b a=-2147483629 b=20
After b=a-b a=-2147483629 b=214
After swap a=20 b=2147483647I think u will find it very interring that after a=a+b the value of a becomes negative

The reason behind->INT_MAX is the max possible value of the integer(this is defined in limits.h and has this value 2147483647 for my C/C++ implementation)and when u add something to it , it can't be positive any more as it crosses the maximum limit of the positive value.So the value of "a" warps around and becomes negative.You can argue at this moment that the end result is same,but its actually implementation defined.You should never depend on implementation defined features unless absolutely necessary as it hurts portability.So lets take another look at this program
#include<stdio.h>
#include<conio.h>
#include<limits.h>
int main()
{
int a=INT_MAX,b=20;
printf("Before swap a=%d b=%d\n",a,b);
a=a^b;
printf("After a=a^b a=%d b=%d\n",a,b);
b=a^b;
printf("After b=a^b a=%d b=%d\n",a,b);
a=a^b;
printf("After swap a=%d b=%d\n",a,b);
_getch();
return 0;
}
Here is the output from console
Before swap a=2147483647 b=20
After a=a^b a=2147483627 b=20
After b=a^b a=2147483627 b=214748
After swap a=20 b=2147483647Here u can see that the values don't change signs during their course.Using XOR(exclusiveor) is the best way to tackle this problem.I will look into XOR in the next section.