Call by Value
|
Call by
Reference
|
1) In this actual copy of arguments is passed
to formal arguments.
|
1) In this location of actual arguments is
passed to formal arguments.
|
2) Any changes made are not reflected in the
actual arguments.
|
2) Any changes made are reflected in the
actual arguments.
|
3) It can only be implemented in C, as C does
not support call by reference.
|
3) It can only be implemented in C++ and
JAVA.
|
4) Actual arguments remain preserved and no
chance of modification accidentally.
|
4) Actual arguments will not be preserved.
|
5) It works locally.
|
5) It works globally
|
#include <stdio.h>
void swapByValue(int, int); /* Prototype */
int main() /* Main function */
{
int n1 = 10, n2 = 20;
/* actual arguments will be as it is */
swapByValue(n1, n2);
}
void swapByValue(int a, int b)
{
int t;
t = a; a = b; b = t;
}
OUTPUT
======
n1: 10, n2: 20
|
#include <stdio.h>
void swapByReference(int*, int*); /* Prototype */
int main() /* Main function */ { int n1 = 10, n2 = 20;
/* actual arguments will be altered */ swapByReference(&n1, &n2); printf("n1: %d, n2: %d\n", n1, n2); }
void swapByReference(int *a, int *b) { int t; t = *a; *a = *b; *b = t; }
OUTPUT
====== n1: 20, n2: 10 |
Friday, 13 October 2017
Difference between call by value and call by reference?
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment