Wednesday, August 15, 2012

Call by Value and Call by Reference in ANSI C.

In ANSI C, variables can be referred directly or indirectly depending on the context.

A variable who is referred indirectly is a variable who is called-by-value. This means that when you pass the variable to a function, a hard copy of the variable will be created and used in that function. Any modifications that occur to the variable while in the function will not happen to the original variable (only the copy will be modified).

A variable who is referred directly is a variable who is called-by-reference. This means that you will send the actual variable to the function using a pointer. Any modifications that occur in the functions will affect the original variable.

Example:
#include<stdio.h>

void CallByValue(int value)
{
    value++;
    printf("Call by value in function     : %d\n",value);
}

void CallByReference(int *value)
{
    (*value)++;
    printf("Call be reference in function : %d\n",*value);
}

int main(int argc, char** argv)
{
    int i = 3;
    printf("Initial value                 : %d\n",i);
    CallByValue(i);
    printf("After call-by-value           : %d\n",i);
    CallByReference(&i);
    printf("After call-by-reference       : %d\n",i);
    return 0;
}
/*Output:
Initial value                 : 3
Call by value in function     : 4
After call-by-value           : 3
Call be reference in function : 4
After call-by-reference       : 4
 */
Observation:
The call by reference mechanism can also be used when you have a large variable to pass. This is especially useful when you work with low-memory systems. If you are not planning to modify the variable you should pass the parameter as a constant:

Example:
void CallByReference(const int *value)
{
    /*The line below would cause a compiler error because the
     value to which the pointer points is indicated as constant*/
    /*(*value)++;*/
    printf("Call be reference in function: %d\n",*value);
}

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger