About Me

My Photo
  • Google Top Contributor - Blogger
  • Google Platinum TC(Mentor) - Tez
  • Google Trusted Tester
  • Software Engineer at Zoho Corporation


I am basically what my tagline says. Dream builder. I build dreams and build those dreams.into reality

Bloggers Profile Twitter Profile
IndiBlogger Profile
What is this? Click here for explanation.

Wednesday, August 14, 2013

Interesting concept that I understood - C++ & C

In functions, we would've heard about Call by reference concept which uses pointers. A simple program to explain "Call by Reference" would be as follows :

void swap(int *a,int *b)
 int temp=*a;
void main()
 int a=10,b=20;
 printf("Before Swap : %d %d",a,b);
 printf("After Swap : %d %d",a,b);

What in it?
In this program, to the function, we pass the address of "a" and "b" , they are stored into two pointers and as we swap the values, the actual value in the main function variables also changes.

Today had an interesting program in my OOPs class during which my staff was explaining "function templates" concept. There is no connection with function templates and what I am going to tell. Read the following program.

void swap(int &x,int &y)

  int temp=x;
void main()
  int a=10,b=20;
  cout<<"Before Swap : "<< a<<" "<<b;

  cout<<"After Swap : "
<< a<<" "<<b;

This program gives the same output as that of the previous program. So, it looks like call by reference, but actually it is not.

What actually happens in this program?
Here, we pass the values to the function but, the function does not only receives the value, but also its address. So, what happens is, same address gets two names. That is it.
  • Let's start from main function.
  • Two Integers a and b are declared and let their addresses be 1000 and 2000 respectively.
  • Their values assigned 10 and 20 respectively.
  • Swap function is called by passing a and b.
  • In the swap function x and y gets values of not only a and b but also their addresses. (i.e) the value and address of a and b gets copied with a new name called x and y respectively. So, this means that the address of x and y are also 1000 and 2000 respectively.
  • Swapping now affects the real values "a" and "b" in main function.
Both of the above programs has the same result, but in different manner. In the first program we pass the "address" and in the second program we pass the "values" only. In first program, passed address gets stored in the pointer, whereas in the second program the memory location itself is assigned with another name. Here the notable thing is that, though x for a and y for b, though looks like another name, has scope aka lifetime only inside the function block "swap."

When I was able to understand this, I really enjoyed the moment. Wished to share the enjoyment.

No comments :

Post a Comment