Easy tutorial for C / C ++ - struct 4 (function call methods)
- We have reviewed the function part by three call
methods: call by value, call by reference, and call by address. All three of
these methods can be applied to struct. Let's look at an example.
Example Code
#include
<iostream>
using
namespace std;
struct
t_Struct{
int num;
char fruit[30];
char color[30];
};
void
C_V(t_Struct);
void
C_A(t_Struct *);
void
C_R(t_Struct &);
int
main() {
t_Struct V1 = {10, "banana" ,
"red"};
t_Struct V2 = {20, "apple" , "black"};
t_Struct V3 = {30, "orange" ,
"white"};
C_V(V1);
t_Struct *pt;
pt = &V2;
C_A(pt);
C_R(V3);
return 0;
}
void
C_V(t_Struct A)
{
cout << " ### Call by value ###
" << endl ;
cout << " number = " <<
A.num << endl ;
cout << " fruit = " << A.fruit << endl ;
cout << " color = " << A.color << endl ;
cout << endl;
}
void
C_A(t_Struct *A)
{
cout << " ### Call by address ###
" << endl ;
cout << " number = " <<
A->num << endl ;
cout << " fruit = " << A->fruit << endl ;
cout << " color = " << A->color << endl ;
cout << endl;
}
void
C_R(t_Struct &A)
{
cout << " ### Call by reference ###
" << endl ;
cout << " number = " <<
A.num << endl ;
cout << " fruit = " << A.fruit << endl ;
cout << " color = " << A.color << endl ;
cout << endl;
}
- We have defined a struct 't_Struct' which has integer
variable 'num' and string variables 'fruit' and 'color' as member variables.
(1) We have declared the function 'C_V' by call by value
method. We got the struct 't_Struct' as a parameter and output the contents of
the member variables of the struct variable that was received as an argument.
(2) We have declared 'C_A' function by call by address
method. The struct pointer variable was taken as argument and the contents of
the member variable of the struct variable are output.
(3) We have declared 'C_R' function by call by reference
method. We took the reference variable as an argument and output the contents
of the member variables of the struct variable.
- Struct variables V1, V2, V3 were
declared and initialized respectively. We first call function 'C_V' with V1 as
its argument.
- The structure pointer
variable 'pt' were declared and substituted the starting address value of the struct
variable 'V2'. And we called function 'C_A' and gave 'pt' as an argument.
Finally, we call the function 'C_R' with the reference variable as an argument.
results
:
###
Call by value ###
number = 10
fruit =
banana
color =
red
### Call by address ###
number = 20
fruit =
apple
color =
black
### Call by reference ###
number = 30
fruit =
orange
color =
white
- You can
see the results by three call methods.
No comments:
Post a Comment