Easy tutorial for C / C ++ - struct 2 (Initial values of struct variables, function arguments,
return value)
- Let's look at how to give initial values to struct
variables. The struct defined in the previous example is:
struct
t_Struct{
int num;
char fruit[30];
char color[30];
};
- Member variables are integer variable 'num' and string
variables 'fruit' and 'color'. Initialization can be done by member variable as
follows. Separate it with a comma (,) and enclose it in curly braces ({}).
ex) :
t_Struct
strA = {5, "banana","white"};
- A struct can be used as a function's return value and
return value. 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
prn_1(t_Struct);
t_Struct
prn_2();
int
main() {
t_Struct strA = {5,
"banana","white"};
cout << "*** \'prn_1\' results
(1st) ***" << endl;
prn_1(strA);
strA = prn_2();
cout << "*** \'prn_1\' results
(2nd) ***" << endl;
prn_1(strA);
return 0;
}
void
prn_1(t_Struct AA)
{
cout << " number = " <<
AA.num << endl ;
cout << " fruit = " << AA.fruit << endl ;
cout << " color = " << AA.color << endl ;
cout << endl;
}
t_Struct
prn_2()
{
t_Struct BB = {7, "apple",
"green"} ;
return BB;
}
- We defined a structure 't_Struct' which has integer
variable 'num' and string variables 'fruit' and 'color' as member variables.
(1) We declare an output function that takes the struct 't_Struct' as an
argument and has no return value. (void prn_1 (t_Struct);) This function
outputs the contents of the member variables of the struct variable received as
an argument.
(2) We declared a function with no argument and a return
value of struct 't_Struct'. (t_Struct prn_2 ();) This function declares and
initializes a struct variable ('BB') and returns {7, "apple",
"green"} structure variables.
- Declared a struct variable 'strA' in the main function and initialized it
with {5, "banana", "white"}. We then called the function
'prn_1' and passed 'strA' as an argument.
- Called 'prn_2 ()' and assigned to 'strA'. And once
again we call the function 'prn_1' and pass 'strA' as an argument.
results
:
***
'prn_1' results (1st) ***
number = 5
fruit =
banana
color =
white
***
'prn_1' results (2nd) ***
number = 7
fruit =
apple
color =
green
- As a
result of the first output, we can see that the initial value 5, banana, white
of the struct variable strA is output.
- The function 'prn_2 ()' is called and the returned value is assigned to 'strA'. As a result, we can see that the initial value 7, apple, green of the struct variables defined in the 'prn_2 ()' function is output.
No comments:
Post a Comment