In order to explain how a structure works, let's look at an example. When calculating a person’s BMI we need multiple pieces of information. We need their weight in pounds, their height in feet and inches, and their name so we can identify them later. In order to compute BMI, we can calculate it using the following equation:
BMI = (703 ∗ weight) ∗ totalHeight^2
Keep in mind that to calculate total height you will need to use the following equation:
totalHeight = feet ∗ 12 + inches
We could store all of this information in multiple variables, but it would be easier to define a new composite datatype that can hold a combination of various primitive datatypes (int, float, double, etc). A struct provides this functionality.
The following program uses individual variables associated with a person’s health information to compute their BMI and determine if it is within a range. Compile and run this code to verify its functionality.
A struct can also be passed to a function as a parameter. The rule for passing a struct as a parameter is the same as that of a simple variable. If you are modifying any of the members of the struct, then you need to pass the struct as call-by-reference. In the above program, we do not modify the variables, so we can pass these to a function as call-by-value.
Now, you will modify the above program to group the four parameters (i.e., name, weight, feet, and inches) into a global struct called Patient. Then, instead of declaring these four variables individually in main, you will declare a variable (or instance) called person of the Patient struct type and read in the values from the keyboard directly into the members of this struct variable. Again, instead of passing the individual variables to the checkBMI function, you will pass the struct variable. And finally, when printing out the name at the end, be sure to use the name stored in the struct variable.