Saturday 15 February 2020

Side Effect of Aliasing with Example

                 In this post, we will see Side Effect of Aliasing with Example


What is Alias?
                  In programming languages, alias is the another name for the variables with same memory allocation. In C++, reference variables are the aliases.

What is the use of creating aliases?
                  Aliases saves the memory space as they point to the memory location of original variable.

What is the side effect of aliasing?
                  Though aliases save the memory, we sometimes may get different / unexpected result.

Check following examples:
                 Following program sideeffectalias.cpp is written to swap the values of two variables a and b.

Program (sideeffectalias.cpp)

#include<iostream>
using namespace std;

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

int main()
{
int a=5,b=3;
swap(a,b);
cout<<"a="<<a<<" b="<<b<<"\n";
}
  
Output (sideeffectalias.cpp)

parag@parag-Inspiron-N4010:~/Desktop/programs$ g++ sideeffectalias.cpp
parag@parag-Inspiron-N4010:~/Desktop/programs$ ./a.out
a=3 b=5
 
                  In above program, swap() function is written to swap the two numbers a and b. Now, let us try to swap a with a. Check following program code.

Program (sideeffectalias.cpp)

#include<iostream>
using namespace std;

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

int main()
{
int a=5,b=3;
swap(a,a);
cout<<"a="<<a<<" a="<<a<<"\n";
}
  
Output (sideeffectalias.cpp)

parag@parag-Inspiron-N4010:~/Desktop/programs$ g++ sideeffectalias.cpp
parag@parag-Inspiron-N4010:~/Desktop/programs$ ./a.out
a=0 a=0
 

                      In above example, many of us will have confusion over the output.We generally expect value of a is 5. If we swap with a with a, we should get a=5. But, we got a=0.
                      Reason is in above code, x and y are the aliases of a. So x=x+y will make a=10. y=x-y will make a=0. Again x=x-y will make a=0.
                      Hence, we got a=0.

                      Conclusion of above discussion is, though aliases are used to save the memory, we have to use them carefully. Otherwise, we may get unexpected results.


No comments:

Post a Comment