thank you. God Bless
Can you please give me a sample program about Turbo C with the topic of "pass by value and pass by reference".
Function pass by value
void f(int n)
{
n = 0; // This changes n to zero
}
int main(void)
{
int i = 5;
printf("Before fn, i = %d\n", i);
f(i); // Pass a copy of i to function f(), f() will not change i.
printf("After fn, i = %d\n", i);
f(10); // This call is valid due to the fact that a copy of the value is passed to f().
}
By reference using pointers.
void f(int *n)
{
*n = 0; // This changes n to zero
}
int main(void)
{
int i = 5;
printf("Before fn, i = %d\n", i);
f(%26amp;i); // Pass a reference of i to function f(), f() will change i.
printf("After fn, i = %d\n", i);
// f(1); is invalid, require a variable for reference to work.
}
In C++, simplier function call by reference.
void f(int %26amp;n)
{
n = 0; // This changes n to zero
}
Call fn() with variables only.
int main(void)
{
int i = 5;
printf("Before fn, i = %d\n", i);
f(i); // Pass a reference of i to function f(), f() will change i.
printf("After fn, i = %d\n", i);
// f(1) will not work, require a variable as argument.
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment