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);
}

About our authors: Team EQA

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

#