Previous: 12.1.2 Using Structure Tags
Up: 12.1 Structures
Next: 12.1.4 Pointers to Structures
Previous Page: 12.1.2 Using Structure Tags
Next Page: 12.1.4 Pointers to Structures
Structure variables may be passed as arguments
and returned from functions just like scalar variables.
Let us consider an example that reads and prints a
data record for a part. The record consists of the part number, its cost and
retail price. (In a later section,
we will see how an inventory for a list of parts can be maintained).
The code to read and print a single part structure is shown
in Figure 12.3.
Notice we have declared the structure template, inventory, at the head of the source file. This is called an external declaration and the scope is the entire file after the declaration. Since all the functions in the file use this structure tag, the template must be visible to each of them. The driver calls read_part() to read data into a structure and return it to be assigned to the variable, item. Next, it calls print_part() passing item which merely prints the values of the structure fields, one at a time. The program is straightforward. A sample session is shown below:
External declarations of structure templates and prototypes facilitate consistent usage of tags and functions. As a general practice, we will declare structure templates externally, usually at the head of the source file. Sometimes, external structure tag declarations will be placed in a separate header file, which is then made part of the source file by an include directive.
From this example, we can see that using structures with functions is no different than using any scalar data type like int. However, let us consider what really happens when the program runs. When the function read_part() is called, memory is allocated for all of its local variables, including the struct inventory variable, part. As each data item is read, it is placed in the corresponding field of part, accessed with the dot operator. The value of part is then returned to main() where it is assigned to the variable item. As would be the case for a scalar data type, the value of the return expression is copied back to the calling function. Since this is a structure, the entire structure (each of the fields) is copied. For our inventory structure, this isn't too bad - only two floats and an integer. If the structure where much larger, maybe including nested structures and arrays, many values would need to be copied.
Likewise with the call to print_part(). Here, an inventory structure is passed to the function. Recall that in C, all parameters are passed by value - the value of each argument expression is copied from the calling function into the cell allocated for the parameter of the called function. Again, for large structures, this may not be a very efficient way to pass data to functions. In the next section we see a way to remedy this problem.