Easy tutorial for C / C ++ - Call by address
Call by by address :
- This is a way to pass the
address value of a variable when calling a function. Let's look at a simple
example.
Example Code
#include <iostream>
using namespace std;
void Call_A(int *);
int main() {
int a ;
a = 4;
cout
<< " Call by by address example " << endl;
cout
<<" (1) In main function :
"<< " a = " << a << ", address
of a = "<< &a << endl;
Call_A(&a);
cout <<" (2) In main function : "<< " a =
" << a << ", address of a = "<< &a
<< endl;
return 0;
}
void Call_A(int *b){
*b += 1;
cout <<" Call by address : "<< " b =
" << *b << ", address of b = "<< &b
<< endl;
}
- The Call_A function with a
parameter which is a pointer variable has been defined. In this case, since the
argument of the prototype of the function is a pointer, '*' is added.
- The Call_A function takes an
address value (int * b) as an argument and increments the value in this address
by one (* b + = 1;). Incremented value and address of pointer variable are
printed.
- Declare the integer variable
'a' in the main function and substitute 4. First, we print the value of 'a' and
the address of variable 'a'.
- When calling the Call_A function, I gave the address value of the variable
'a' as an argument (Call_A (& a);). And once again the value and address of
the variable 'a' are printed.
results :
Call by by address example
(1) In main
function : a =
4, address of a = 0x7fff1012ca1c
Call by
address : b =
5, address of b = 0x7fff1012c9e8
(2) In main
function : a =
5, address of a = 0x7fff1012ca1c
- On the first line, "Call by by address
example" is printed.
- On the second line, the value
(a = 4) and the address value (0x7fff1012ca1c) assigned to the variable 'a'
defined by the main function are printed.
- The third line shows the
result of the function Call_A created by 'call by address' method. The value of
pointer variable 'b' is incremented by 1 (b = 5) and the address value of
pointer variable 'b' (0x7fff1012c9e8) is also printed. It is different from the
address value of the variable 'a' defined in the main function.
- The last line shows the result of the variable 'a'
in the main function. You can see that the value of variable 'a' has been
changed to 5. Of course, the address value is the same value as the first line,
and only the value stored in 'a' is changed.
No comments:
Post a Comment