Calling conventions is important concepts in computer languages. It defines a way in which parameters are transferred between one functions when one function calls another. There are the major types of parameter passing.
1) Call by Value:-
In this mechanism, a copy of each actual parameter is passed to a called function and stored into a corresponding formal parameter. So if a called function modifies the formal parameter, it does not affect the actual parameter or say the originally passed values. Here since the mechanism only copies data from the caller, the actual parameter can be any expression or variable.
void increment(int a) { a++; } main() { int p=10; increment (p); printf(“%d”,p); }
In above C program value of variable p will remain 10 because when we call function increment(), copy of value of variable p will be copied to local variable a of function increment(). So value of p will not be affected. In Java it is default mechanism.
2) Call by reference:-
In this mechanism, a caller passes the reference of each actual parameter. So the caller function and called function both works on same copy of data. When a called function modifies the value of formal parameter, originally passed actual parameter is also affected because both working on same data. This mechanism performs better compared to Call by value .In C pointers can be used to use this mechanism. It can be used when large object has to be passed as function argument to save memory. When using this mechanism only variable can be passed and expression can’t be passed. In C++ a const keyword can be used to use this mechanism with constraint that value should not be modified.
void print(int const& x) { x = 2; // This is not allowed. cout << x ; }
Example C function
void increment(int *a) { (*a)++; } main() { int b=10; increment (&b); printf("%d",b); }
In above program, a value of variable b will be 11 because we have passed reference of b and so in turn function increment() works on same copy.
3) Call by value-result:-
This mechanism can be said as a combination of both Call by value and Call by reference. In this mechanism same like Call by value copy of actual parameter is passed to a corresponding formal parameter. If called function modifies a formal parameter, actual parameter is not affected but when function returns, the value of formal parameter is copied back to actual parameter. Here also like Call by reference, the called function copies data to called function parameter, the passed value can only be variable and not any expression. This mechanism is available in Ada.
Other mechanisms like call by copy-restore, call by need , call by name are also available but they are not widely used.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.