Structure can be passed via call by value or call by reference. This gives two choices for the developer. Let's us see two examples here.

struct student_t {
  unsigned int Roll;
  char name[MAX_STRING];
  unsigned Int age;
};

Call by value example:
void display_record (const student_t s){
  printf ("Student Name: %s\n", s.name);
  printf ("Roll No#%d, Age %d\n", s.roll, s.age);
}

Now call by value is achieved by copying the content of original structure into the stack and pass this to the subroutine. Here it is obvious that we cannot change the content of the original structure. Thus changing the original variable/structure content requires structure to be passed as reference. Letís see our next example.

Call by reference:
void input_record (student_t * s_ptr ){
  printf ("Enter Student Name: ");
  scanf ("%s",  s_ptr ->name);
  printf ("Roll No#%d, Age %d\n", s_ptr ->roll, s_ptr ->age);
  scanf ("%s",  s_ptr ->name);

}

Passing by reference is needed when we need to change some or all members of the structure. Again passing reference means just passing the address of the struct variable to the sub-routine and subroutine de-reference the content.

void display_record (student_t * s_ptr ){
  printf ("Student Name: %s\n", s_ptr ->name);
  printf ("Roll No#%d, Age %d\n", s_ptr ->roll, s_ptr ->age);
}

Here copying the content of struct is not required and thus it is fast, takes less stack thus safer, and it gives less overhead to the compiler. Hence call by value is always preferred over call by value even if we donot require to modify the content or use it as call by value. We most often declare const pointer of struct for arguments in these cases. Const keyword says it is input argument or only de-reference for reading is allowed.

void display_record (const student_t * s_ptr ){
  printf ("Student Name: %s\n", s_ptr ->name);
  printf ("Roll No#%d, Age %d\n", s_ptr ->roll, s_ptr ->age);
}

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

calling convention of C,C++ and PASCAL, library function linking, call-by-value and call-by-reference, parameter passing call-by-value, parameter passing call-by-reference, structure as function argument, array as function argument, inline-functions, macro vs inline-function, function pointer,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan