-->

Structures and Functions

Structures and Functions
·         C language 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.
1.       The first method is to pass each member of the structure as an actual argument of the function call.
o   The actual arguments are then treated like ordinary variables.
o   This method is inefficient when the structure size is large.
2.       Passing of a copy of the entire structure to the called function.
o   Since the function is working on a copy of the structure, any changes to the structure members within the function are not reflected on the original structure (in the calling function).
o   It is necessary for the function to return the entire structure back to the calling function.
o   All compilers do not support this method of passing the entire structure as a parameter.
3.       Pointers to pass the structure as an argument.
o   In this the address of the structure is passed on to the called function.
o   The function can access directly the entire structure and work on it.
o   This method is more efficient as compared to the second one.
o   The general format of sending a copy of a structure to the called function is, function-name (structure variable - name);
o   The called function takes the following form.
data - type function - name(struct - type variable - name)
{
-------------------
-------------------
return (expression);
}
Points to be remembered:

  1. The called function must be declared for its type, appropriate to the data type it is expected to return.       Example: If it returns a copy of the entire structure, then it must be declared as a struct with an appropriate tag name. 
  2. The structure's variable name, which is used as the actual parameter 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. 
  4. The expression may be a simple variable or structure variable or an expression of a data back to the calling function. 
  5. When a function returns a structure, it must be assigned to a structure of an identical type in the calling function. 
  6. The called functions must be declared in the calling function appropriately.

Related Posts

Subscribe Our Newsletter