How to Pass Structure Values as Parameters to Functions?


C supports the passing of structure values as arguments to functions. There are 3 methods by which the values of a structure can be transferred from one function to another.

1. The 1st method is to pass each member of the structure as a actual argument Of the from 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.

2. The 2nd 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.

It is therefore necessary for the function to return the entire structure back to the calling function. All compilers may not support this method of passing the entire structure as a parameter.

3. The 3rd approach employs a concept  called pointers to pass the structure 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 function. This method is more efficient as compared to the second one.

The general format of sending a copy of a structure to the called function is:

function_name (structure_variable_name);  // function.call.

The called function takes the following form

datatype function-name ( struct –type, st-name)
{
………………………
……………………..
return ( exp);
}

The follow points are important to note:

1. The called function must be declared for its type, appropriate to the data type it is expected to return.

For ex: if it is returning a copy of the entire structure with an appropriate tag name.

2. The structure variable used as the actual argument And the corresponding formal argument In the called function Must be  of the same struct type.

3. The return statement is necessary only when the function is returning some data back to the calling function. The expression may be any simple variable or structure variable or an expression is using simple variables.

4. When a function returns a structure, it must be assigned to a structure of identical type in the calling function.

5. The called functions must be declared in the calling function Appropriately.

Related

C Language 1611896406499853493

Post a Comment

emo-but-icon

item