|
You have learned everything you need to do this in C
Consider the following example:
#include <stdio.h> // DEMO this program
void f(int x)
{
x = x + 1;
}
int main(int argc, char *argv[])
{
int a = 4;
printf("Before calling f(a), a = %d\n", a);
f(a);
printf("After calling f(a), a = %d\n", a);
}
|
C will pass the value of the variable a to function f( )
We can pass the address (value) of the variable a using &a:
#include <stdio.h> void f(int x) { x = x + 1; } int main(int argc, char *argv[]) { int a = 4; printf("Before calling f(a), a = %d\n", a); f(&a); // Pass the value of the address of var a printf("After calling f(a), a = %d\n", a); } |
However: the data type of the parameter int x is now incorrect.
The correct type is int *x because x stores an address of an int typed variable:
#include <stdio.h> void f(int *x) { x = x + 1; } int main(int argc, char *argv[]) { int a = 4; printf("Before calling f(a), a = %d\n", a); f(&a); printf("After calling f(a), a = %d\n", a); } |
However: the
statement
x = x + 1
says:
use the
variable x in
an addition
x is
not an
variable that you can
use for addition !!
(x
contains an
address !!)
The statement
x = x + 1
must be
changed to:
use the
variable
at the address
given by x !!!
The correct statement is *x = *x + 1 because *x is an alias of the int typed variable a:
#include <stdio.h> // DEMO this program void f(int *x) { *x = *x + 1; } int main(int argc, char *argv[]) { int a = 4; printf("Before calling f(a), a = %d\n", a); f(&a); printf("After calling f(a), a = %d\n", a); } |
And this is how C achieves the effect of the pass-by-reference mechanism (DIY) !!!
When we pass the address &a as parameter:
#include <stdio.h> void f(int *x) // x will contain &a !! { // It's as if the program has executed: x = &a; *x = *x + 1; } int main(int argc, char *argv[]) { int a = 4; printf("Before calling f(a), a = %d\n", a); f(&a); printf("After calling f(a), a = %d\n", a); } |
The parameter variable
x will
contain
&a.
Therefore:
*x will be an
alias for
a
and
*x = *x + 1 will
update
the variable a
|
Situation where you need to use function declaration:
#include <stdio.h> int main(int argc, char *argv[]) { int a = 4; printf("Before calling f(a), a = %d\n", a); f(&a); // Call function before it's defined printf("After calling f(a), a = %d\n", a); } void f(int *x) { *x = *x + 1; } |
Situation where you need to use function declaration:
#include <stdio.h> void f(int *x); // Declare function int main(int argc, char *argv[]) { int a = 4; printf("Before calling f(a), a = %d\n", a); f(&a); // No error now printf("After calling f(a), a = %d\n", a); } void f(int *x) { *x = *x + 1; } |