As we know that the main philosophy of C language is the use of functions. Therefore, it is natural that C supports the passing of structure values as arguments to functions. There are three methods by which the values of a structure can be transferred from one function to another.
The first method is to pass each member of the structure as an actual argument of the function call. The actual arguments are then treated independently like ordinary variables. This is the most elementary method and becomes unmanageable and inefficient when the structure size is large.
The second method involves passing of a copy of the entire structure to the called function. Since the function is working on a copy of the structure, any changes to structure members within the function are not reflected in the original structure (in the calling function). It is, therefore, necessary for the function to return the entire structure bask to the calling function. All compilers may not support this method of passing the entire structure as a parameter.
The third approach employs a concept called pointers to pass the structure as an argument. In this case, the address location of the structure is passed to the called function. The function can access indirectly the entire structure and work on it. This is similar to the way arrays are passed to the functions. This method is more efficient as compared the second one.
For second method:
The general syntax for sending a copy of a structure to the called function is:
function_name(structure variable name);
Similarly, the syntax for the called function will be:
return_type function_name(structure name)
- The called function must be declared for its type, appropriate to the data type it is expected to return. For example, if it is returning a copy of the entire structure, then it must be declared as struct with an appropriate tag name.
- The structure variable used as the actual argument and the corresponding formal argument in the called function must be of the same struct type.
- The return statement is necessary only when he function is returning some data. The expression may be any simple variable or structure variable or an expression using simple variables.
- When a function returns a structure, it must be assigned to a structure of identical type in the calling function.
- The called function must be declared in the calling function for its type, if it is placed after the calling functions.