Loading

About Me

My Photo
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 :

#include<stdio.h>
void swap(int *a,int *b)
{
 int temp=*a;
*a=*b;
*b=temp;
}
void main()
{
 clrscr();
 int a=10,b=20;
 printf("Before Swap : %d %d",a,b);
 swap(&a,&b);
 printf("After Swap : %d %d",a,b);
 getch();
}

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.

#include<stdio.h>
#include<conio.h>
void swap(int &x,int &y)

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

  swap(a,b);
  cout<<"After Swap : "
<< a<<" "<<b;
  getch();
}

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