Monday, February 2, 2009

Pass it by referance......

"How many parameter passing mechanisms are there in C ?"
This was the question raised by Vineeth sir in the middle of a class.
I am extremely shameful in stating that none except one(obviously it's Sangeeth) knew the answer.
Yes it's in the same NITC Compsci Department,which is ranked as one of the best in India.

Well, if you are also the one who doesnot know the answer , then carry on reading ,else come back for my next post.

The answer is 1.
You have only pass by value in 'C'

In C++ I suppose the answer is 2.
Pass by value and Pass by reference.

int f1(int a)
{
...

...

}

int f2()
{
int x;
.....
...
f1(x);
.....
}


Obviously the above program is an example of call by value. Nobody has any doubt there. And me too didnot have either.
But the problem was here.

int f1(int * a)
{
...
...
}
int f2()
{
int x;
.....

f1(&x);
......
}
But should I call it ? Call by value or Call by reference.
Certainly it is call by value.Have any doubts?Then a bit more clarification. '&x' is an expression.Its value is the address of x.
And it is this value that is being passed.

Now moving on to C++,we have Call by reference.

int f1(int &a)
{
...
...
}

int f2()
{
int x;
...
f1(x);
...
}

I suppose it was an added feature in C++ . But C is not lacking , sice it could acheive
the merits of call by reference through "the powerfull pointers".

Well, that sums it up.Thank you for reading my first technical entry.

Signing off
RK

No comments: