Sunday 1 July 2012

Call by Value and Call by Reference & Recursion

Call by Value and Call by Reference:


In C programming language, variables can be referred differently depending on the context. For example, if you are writing a program for a low memory system, you may want to avoid copying larger sized types such as structs and arrays when passing them to functions. On the other hand, with data types like integers, there is no point in passing by reference when a pointer to an integer is the same size in memory as an integer itself.
Now, let us learn how variables can be passed in a C program.

Pass By Value:

Passing a variable by value makes a copy of the variable before passing it onto a function. This means that if you try to modify the value inside a function, it will only have the modified value inside that function. One the function returns, the variable you passed it will have the same value it had before you passed it into the function.

Pass By Reference:

There are two instances where a variable is passed by reference:
  1. When you modify the value of the passed variable locally and also the value of the variable in the calling function as well.
  2. To avoid making a copy of the variable for efficiency reasons.

Recursion:

A function that calls itself is known as recursive function and the process of calling function itself is known as recursion in programming.

Advantages and Disadvantages of Recursion:

Recursion is more elegant and requries few variables which make program clean and easy to understand. Recursion can be used to replace complex nesting code by dividing the problem into same problem of subtype.
In other hand, it is hard to think the logic of a recursive function. It is also difficult to debug the code containing recursion.





No comments:

Post a Comment